using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using static Easily.Icon;
using System.Media;
using static Easily.frmIconBox;
using WeifenLuo.WinFormsUI.Docking;

namespace Easily
{
    /// <summary>
    /// 该类主要提供了编程面板中涉及到的一些要素：曲线、相互连接、保存工程、打开工程等操作
    /// </summary>
    public partial class frmGraphicProgrammer : DockContent
    {
        [DllImport("User32.dll", EntryPoint = "GetKeyState")]
        private static extern int GetKeyState(int nVirtKey);  //用于实现滚轮效果，判断鼠标按键    

        #region frmGraphicProgrammer类的字段
        ///==============================================================================

        MDIParentFrame frmParent = new MDIParentFrame();

        //记录当前选中的控件图标的信息
        public LineLinkIconType SelectedIconType;//当前选中的控件的类型
        public int SelectedIconNum;//当前选中的控件在相应控件数组中的下标位置
        public Icon SelectedIcon;//当前选中的控件
        public ArrayList SelectedIconArr = new ArrayList();//当前选中的控件组

        //图标控件数组
        public ArrayList IconGeneralArr = new ArrayList();//存放已经放在图形化窗体中的通用控件
        //用于判断是否需要在isr中加入gpio中断
        public ArrayList gpioEventControl = new ArrayList();//存储所有GPIO事件控件
        //[2021/3/31]
        //用于判断是否需要在isr中加入串口中断
        public ArrayList uartEventControl = new ArrayList();//存储所有串口事件控件
        //用于判断是否需要在isr中加入UE中断
        public ArrayList UEcomEventControl = new ArrayList();//存储所有串口事件控件
        //用于判断是否需要在isr中加入定时器中断
        public ArrayList timeEventControl = new ArrayList();//存储所有定时器事件控件

        //变量信息
        public ArrayList m_VariableSys = new ArrayList();//全局变量
        //局部变量 传感器需要字典来存储控件和局部变量的对应关系 以便删除控件时 删除局部变量
        public Dictionary<string, string> m_Sensor_VariableLocal = new Dictionary<string, string>();
        //局部变量
        public ArrayList m_VariableLocal = new ArrayList();
        //public ArrayList m_VariableLocal = new ArrayList();//局部变量

        public ArrayList m_FunDefine = new ArrayList();//终端程序中定义的函数

        public bool BFirstClickOutDot;//首次单击窗体中控件的接出点

        //[2021/4/28]加入音效播放
        readonly SoundPlayer sp = new SoundPlayer();

        public class Hard_Connect
        {
            public string J1;
            public string J2;
            public string J3;
            public string J4;
            public string J5;
            public string J6;
            public string J7;
            public string J8;
            public string JCar;//J9&J10
            
            public Hard_Connect()
            {
                J1 = ""; J2 = ""; J3 = ""; J4 = "";
                J5 = ""; J6 = ""; J7 = ""; J8 = "";
            }
        }
        //[2021/1/30 保存配置终端信息]
        public Hard_Connect hard_Connect;
        ///// <summary>当前的程序类型</summary>
        public ProgrammerDocumentType ProgrammerType; // /
        public SubFunctionType TypeOfSubFunction;
        public string IntSubFuncNum; //保存中断子程序号

        /// <summary>程序信息</summary>
        /// <summary>程序的名字</summary>
        public string ProgrammerName;

        /// <summary>程序的路径</summary>
        public string ProgrammerPath;

        /// <summary>变量初始化代码</summary>
        public string InitVariable = string.Empty;
        /// <summary>模块初始化代码</summary>
        public string InitModule = string.Empty;


        /// <summary>For循环变量初始化代码</summary>
        public ArrayList ForVariable = new ArrayList();

        /// <summary>模块数据变量数组,保存AD模块、红外模块、IO模块等读取的数据20151216</summary>
        public ArrayList ModuleVariable = new ArrayList();

        /// <summary>记录当前窗体中的子程序信息</summary>
        public ArrayList SubInfo = new ArrayList();

        private ContextMenuStrip FlowContextMenuStrip = new ContextMenuStrip();//快捷菜单

        //与控件连接相关的变量声明
        public LineLinkIconType m_OutIconModule;//连出的控件的类型
        public int m_OutIconModuleNum; //连出的控件在其相应链表中的位置
        public LineLinkIconType m_InIconModule;//连入的控件的类型
        public int m_InIconModuleNum;  //连入的控件在其相应链表中的位置
        public CdnjudgeEndInLinkType m_CdnJudgeInDotModule;//条件判断end控件连入的连入点类型
        public CdnjudgeOutLinkType m_CdnJudgeOutDotModule;//条件判断if控件连出的连出点类型
        public LoopInLinkType m_LoopInDotModule;//循环控件的连入点类型
        public LoopOutLinkType m_LoopOutDotModule;//循环控件的连出点类型
        public SwitchOutDotType m_SwitchOutDotModule;//Switch控件连出点类型
        public SwitchInDotType m_SwitchInDotModule;//Switch控件连入点类型
        public Icon m_OutIcon;//记录当前要连出的控件
        public Icon m_InIcon;//记录当前要连入的控件

        //记录画连接线的点的起始坐标
        public float lineStartX;//连接线的起始点的x坐标
        public float lineStatrY;//连接线的起始点的y坐标
        public float lineEndX;//连接线的结束点的x坐标
        public float lineEndY;//连接线的结束点的y坐标

        //画范围框的时候的起始点
        private int PointSelectX;
        private int PointSelectY;
        private bool PointStartSelect;
        //粘贴图标的起始位置
        public int PastPointX=0;
        public int PastPointY=0;

        //绘制连接线的画笔的样式
        //private float baseValue;//贝塞尔曲线的拐点因子1
        //private float facter;//贝塞尔曲线的拐点因子2

        ///==============================================================================
        #endregion

        #region frmGraphicProgrammer类的方法
        ///==============================================================================
        
        /// <summary>默认构造函数</summary>
        public frmGraphicProgrammer()
        {
            try
            {
                InitializeComponent();

                hard_Connect = new Hard_Connect();
                //初始化当前在设计面板中选中的控件的信息
                this.SelectedIcon = null;
                this.SelectedIconType = LineLinkIconType.NULL;
                this.SelectedIconNum = -1;

                this.SetStyle(ControlStyles.ResizeRedraw, true);
                this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
                this.SetStyle(ControlStyles.UserPaint, true);
                this.UpdateStyles();

                BFirstClickOutDot = false;
                PointStartSelect = false;

                ForVariable.Clear();//变量数组清空
                //[20210521]未使用到该模块
                //ModuleVariable.Clear();//模块变量数组清空 
                //ModuleVariable.Add("IRkeyValue");//添加红外遥控按键变量  

                FlowContextMenuStrip.Items.Add("粘贴");//快捷菜单 //20160317
                FlowContextMenuStrip.ItemClicked += new ToolStripItemClickedEventHandler(FlowContextMenuStrip_ItemClicked);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        /// <summary>设置图标之间的相对位置关系，让相连的图标排成一列  20151206 【zsl】</summary>
        public void SetRelation(GeneralIcon Icon)
        {
            GeneralIcon tempIcon;
            tempIcon = Icon;
            //避免环状连接，所造成的死循环.这里或的关系是不正确的，如指向null时，也是不等于Icon
           // while ((tempIcon.Child != null) || (tempIcon.Child != (GeneralIcon)Icon))
            while (tempIcon.Child != null)
            {
                //===========20151206调整连入控件图标的位置，让它们排成一列，间距为5个点.
                ((GeneralIcon)(tempIcon.Child)).IconLeftDotNum = ((GeneralIcon)tempIcon).IconLeftDotNum;
                ((GeneralIcon)(tempIcon.Child)).IconTopDotNum = ((GeneralIcon)tempIcon).IconTopDotNum + 5;
                ((GeneralIcon)tempIcon).ChildDotX = ((GeneralIcon)tempIcon.Child).IconLeftDotNum;
                ((GeneralIcon)tempIcon).ChildDotY = ((GeneralIcon)tempIcon.Child).IconTopDotNum + 2;
                //(tempIcon.Child).IconPicBox.Refresh();
                //(tempIcon.Child).MoveToIconPicBox.Refresh();
                int Num = ((GeneralIcon)tempIcon).ChildIconArrNum;//保留空控件的数组编号
                tempIcon = (GeneralIcon)tempIcon.Child;
                if (tempIcon == (GeneralIcon)Icon)
                {
                    ((GeneralIcon)IconGeneralArr[Num]).Child = null;
                     break;   //避免环状连接，所造成的死循环
                }
            } 
         }           

//=========================================================================

        /// <summary>设置图标之间的链接关系 2015-5-16 【GZF】</summary>
        public void SetDrawRelation()
        {
           int LSChildIconArrNum=0;//控件的子控件在其相应链表中的位置
           GeneralIcon tempIcon;
            
            try
            {
                Globaldefine.FrmParent.ModifyProgrammer = true;
                    
                    //连出的控件是通用控件
                    //如果连出的通用控件有子控件
                  if (((GeneralIcon)m_OutIcon).Child != null)
                  {
                     LSChildIconArrNum = ((GeneralIcon)m_OutIcon).ChildIconArrNum; //160125保存输出节点的子节点在数组中的下标  
                    ((GeneralIcon)m_OutIcon).ResetChild((GeneralIcon)m_OutIcon);  //如果连出的通用控件有子控件,则清父子关系和相关属性
                    tempIcon = (GeneralIcon)IconGeneralArr[LSChildIconArrNum];
                    while (tempIcon.Child != null)  //20160317 查找输出节点的子节点是否与输入节点m_InIcon相连，若相连不必连入输出节点子节点
                    {                               //跳过该节点，避免循环出现
                        if (tempIcon.Child == (GeneralIcon)m_InIcon)
                        {
                            ((GeneralIcon)tempIcon).ResetChild((GeneralIcon)tempIcon);  //说明不是连入新节点，而是除去已经连入的节点
                            LSChildIconArrNum = 0;
                            break;
                        }
                        tempIcon = (GeneralIcon)tempIcon.Child;
                    }
                  }
                    //根据连入控件的类型进行相关设置,确定画连接线位置点
                   //如果要连入的控件已经有父控件,则清除父控件的连出标志
                   ((GeneralIcon)m_InIcon).ResetParent((GeneralIcon)m_InIcon);
                   //置连入和连出控件的父子关系
                   ((GeneralIcon)m_InIcon).Parent = (GeneralIcon)m_OutIcon;
                   ((GeneralIcon)m_InIcon).ParentIconArrNum = m_OutIconModuleNum;
                   ((GeneralIcon)m_InIcon).ParentType = GeneralIcon.LinkIconType.GeneralIcon;                  
                
                   ((GeneralIcon)m_OutIcon).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                   ((GeneralIcon)m_OutIcon).Child = (GeneralIcon)m_InIcon;
                   ((GeneralIcon)m_OutIcon).ChildIconArrNum = m_InIconModuleNum;
                   ((GeneralIcon)m_OutIcon).ChildDotX = ((GeneralIcon)m_InIcon).IconLeftDotNum;
                   ((GeneralIcon)m_OutIcon).ChildDotY = ((GeneralIcon)m_InIcon).IconTopDotNum + 2;
                   if (LSChildIconArrNum != 0)//说明要连接输出节点的后续节点
                   {
                       tempIcon = (GeneralIcon)m_InIcon;
                       while (tempIcon.Child != null)
                       {//===========20160125 查找与连入节点相连的最后一个节点
                           tempIcon = (GeneralIcon)tempIcon.Child;
                       }
                       ((GeneralIcon)tempIcon).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                       ((GeneralIcon)tempIcon).Child = (GeneralIcon)IconGeneralArr[LSChildIconArrNum];
                       ((GeneralIcon)tempIcon).ChildIconArrNum = LSChildIconArrNum;
                       ((GeneralIcon)tempIcon).ChildDotX = ((GeneralIcon)IconGeneralArr[LSChildIconArrNum]).IconLeftDotNum;
                       ((GeneralIcon)tempIcon).ChildDotY = ((GeneralIcon)IconGeneralArr[LSChildIconArrNum]).IconTopDotNum + 2;
                       //20160331必须加入父亲关系，否则删除该控件时，撤销关系不正确
                       ((GeneralIcon)IconGeneralArr[LSChildIconArrNum]).Parent = tempIcon;
                       ((GeneralIcon)IconGeneralArr[LSChildIconArrNum]).ParentIconArrNum = tempIcon.IconArrNum;
                       ((GeneralIcon)IconGeneralArr[LSChildIconArrNum]).ParentType = GeneralIcon.LinkIconType.GeneralIcon; 
                   }    
                this.CreateCode();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        /// <summary>绘制编程面板区域的所有连线 2015-5-16  【GZF】</summary>        
        /// <param name="bg">图形化编程面板</param>
        public void ReDrawLine(BufferedGraphics bg)
        {
            int i;

            try
            {
                Pen pen = new Pen(Brushes.Black, Globaldefine.DotSize * 6)
                {
                    EndCap = LineCap.ArrowAnchor
                };
                //(1) 通用控件
                for (i = 0; i < IconGeneralArr.Count; i++)
                {
                    if (((GeneralIcon)IconGeneralArr[i]).Child != null)
                    {                //画直线不区分kzIconLoop类型，统一画线
                        bg.Graphics.DrawLine(pen, 
                            (int)((((GeneralIcon)IconGeneralArr[i]).IconLeftDotNum +4) * Globaldefine.DotSize * 15),
                            (int)((((GeneralIcon)IconGeneralArr[i]).IconTopDotNum+3) * Globaldefine.DotSize * 15),
                            (int)((((GeneralIcon)IconGeneralArr[i]).ChildDotX+4)* Globaldefine.DotSize * 15),
                            (int)((((GeneralIcon)IconGeneralArr[i]).ChildDotY-2) * Globaldefine.DotSize * 15));
                    }
                }
                if (this.BFirstClickOutDot)
                {
                    //20151205改用系统提供的直线函数
                    bg.Graphics.DrawLine(pen,
                        new Point((int)this.lineStartX,(int)this.lineStatrY),
                         new Point((int)this.lineEndX,(int)this.lineEndY));                          
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
                
        /// <summary>生成.C文件存储程序代码</summary>  <param name="FilePath">文件路径</param>
        public void SaveCodeOfFunc(string FilePath)
        {
            //生成程序代码
            this.CreateCode();
            FilePath.Replace("  ","");
            FilePath.Replace("\0", "");
            //生成.C文件存储程序代码
            //D:\0图形化\Easily-190624\bin\Debug\Project\MKL36Z64xxx4\KDS\Source\07_NosPrg\main.c
            //D:\0图形化\Easily-190624\bin\Debug\Project\MKL36Z64\KDS\Source\07_NosPrg\main.c
            Globaldefine.FrmParent.CodeOfForm.text_main.SaveFile(@FilePath + @"\main.c");
            Globaldefine.FrmParent.CodeOfForm.text_isr.SaveFile(@FilePath + @"\isr.c");
            Globaldefine.FrmParent.CodeOfForm.text_includes.SaveFile(@FilePath + @"\includes.h");
        }

        

        /// <summary>重新刷新图形化编程面板中的连线，借助BufferedGraphics  2015-5-16 【GZF】</summary>
        public void ReDraw(BufferedGraphics bg)
        {
            try
            {
                int i;

                bg.Graphics.Clear(this.BackColor);
                //ReDrawBgLine(bg);
                ReDrawLine(bg);
                if (this.SelectedIcon != null)
                {
                    //((Icon)SelectedIcon).IconPicBox.BackColor = Color.Red;
                    ((Icon)SelectedIcon).IconPicBox.BackColor = Color.AliceBlue;
                }
                for (i = 0; i < SelectedIconArr.Count; i++)
                {
                    //((Icon)SelectedIconArr[i]).IconPicBox.BackColor = Color.Red;
                    ((Icon)SelectedIconArr[i]).IconPicBox.BackColor = Color.AliceBlue;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
       
        /// <summary>重新刷新图形化编程面板中的连线，不借助BufferedGraphics  2015-5-16 【GZF】</summary>
        public void ReDraw()
        {
            try
            {
                int i;
                Graphics g = this.CreateGraphics();
                BufferedGraphicsContext context = BufferedGraphicsManager.Current;//当前应用程序域的图像缓冲区
                BufferedGraphics bg = context.Allocate(g, this.ClientRectangle);//得到可用于绘制到指定尺寸的缓冲区
                bg.Graphics.Clear(this.BackColor);
                //ReDrawBgLine(bg);//重绘图形化编程面板画上格子线
                ReDrawLine(bg); //重绘制编程面板区域的所有连线 
                if (this.SelectedIcon != null)
                {
                    //((Icon)SelectedIcon).IconPicBox.BackColor = Color.Red;
                    ((Icon)SelectedIcon).IconPicBox.BackColor = Color.AliceBlue;
                }
                for (i = 0; i < SelectedIconArr.Count; i++)
                {
                    //((Icon)SelectedIconArr[i]).IconPicBox.BackColor = Color.Red;
                    ((Icon)SelectedIconArr[i]).IconPicBox.BackColor = Color.AliceBlue;
                }

                bg.Render();// 将图形缓冲区的内容写入默认设备。
                bg.Dispose();
                bg = null;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
       
        /// <summary>按照编程面板中连接方式生成右侧的代码 2015-5-16 【GZF】</summary>
        public void CreateCode()
        {
            try
            {
                //int i;
                string txt_main = string.Empty;
                string txt_isr = string.Empty;
                string txt_includes = string.Empty;
                string temp;
                int iTemp = 0;

                //[20210420]-hsc 不同的使用NB的模块，其userdata和定义的全局变量都不一样，
                //需要一个变量来判断，当前控件中是否存在对应的NB模块
                //对每个模块，进行单独处理
                bool isCrutch = false;//是否使用智能拐杖
                bool isFridge = false;//是否使用可控冰箱
                if (Globaldefine.FrmParent.IsAdvanceMode) return; //若为高级模式，则不生成代码
                if (this.ProgrammerType == ProgrammerDocumentType.MainFun)
                {
                    //main.c文件
                    txt_main =
                        "//======================================================================\r\n"
                      + "//文件名称：main.c\r\n"
                      + "//功能概要：应用工程主函数及部分子函数\r\n"
                      + "//版权所有：苏大arm技术中心(sumcu.suda.edu.cn)\r\n"
                      + "//版本更新：2017.08:1.0, 2019.1:A.10\r\n"
                      + "//功能描述：说明见工程文件夹下的Doc文件夹内Readme.txt文件\r\n"
                      + "//======================================================================\r\n"
                      + "#define GLOBLE_VAR                     //定义全局变量宏标识\r\n"
                      + "#include \"includes.h\"                  //包含总头文件\r\n"
                      + "//----------------------------------------------------------------------\r\n"
                      + "//【根据实际需要增删】声明使用到的内部函数\r\n"
                      + "//main.c使用的内部函数声明处\r\n";
                    //txt_main += "//【根据实际需要增删】子函数代码\r\n";
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        if (icon.ModuleName == "智能拐杖-NB")
                            isCrutch = true;
                        if (icon.ModuleName == "冰箱-NB")
                            isFridge = true;
                        if (icon.code.SubfunctionDeclare != "")
                            txt_main += icon.code.SubfunctionDeclare + "\r\n";
                    }
                    txt_main += "//----------------------------------------------------------------------\r\n"
                        + "//主函数，一般情况下可以认为程序从此开始运行（实际上有启动过程见书稿）\r\n"
                        + "int main(void)\r\n"
                        + "{\r\n"
                        + "\t////=======================（1）启动部分（开头）=======================\r\n"
                        + "\t//（1.1）声明main函数使用的局部变量\r\n";
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        if (icon.code.LocalVariable != "")
                        {
                            txt_main += "\t" + icon.code.LocalVariable;
                            //取出变量前的类型 只保留变量名
                            //[2021/03/26]传感器的变量加入了m_Sensor_VariableLocal中 不需要在这里处理
                            //[2021/4/1]重新处理变量名
                            if (!icon.ModuleName.Contains("传感器"))
                            {
                                //去除变量类型
                                string nameRedun = icon.code.LocalVariable.Split(' ')[1];
                                //去除分号后注释
                                string varName = nameRedun.Split(';')[0];
                                if (!m_VariableLocal.Contains(varName))
                                    m_VariableLocal.Add(varName);
                            }
                        }
                    }
                    txt_main += "\t//（1.2）初始化main函数使用的局部变量和全局变量\r\n";
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        if (icon.code.InitVariable != "")
                            txt_main += "\t" + icon.code.InitVariable + "\r\n";
                    }
                    txt_main += "\t//（1.3）【不变】 关总中断\r\n"
                        + "\tDISABLE_INTERRUPTS;\r\n"
                        + "\t//（1.4）【不变】获取BIOS构件接口并设置中断服务例程\r\n";
                    txt_main += "\t//（1.5）用户外设模块初始化\r\n";
                    temp = "";
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        if (icon.code.Initialization != "")
                        {
                            if (temp.Contains(icon.code.Initialization)) //防止语句重复
                                continue;
                            temp += "\t" + icon.code.Initialization + "\r\n";
                        }
                    }
                    txt_main += temp;
                    txt_main += "\t//（1.6）使能模块中断\r\n";
                    //增加使能模块中断代码
                    temp = "";
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        //parent的判定没有必要icon.Parent == null && 
                        if (icon.code.InterruptEnable != "")
                        {
                            if (temp.Contains(icon.code.InterruptEnable))//防止语句重复
                                continue;
                            temp += "\t" + icon.code.InterruptEnable + "\r\n";
                        }
                    }
                    txt_main += temp;

                    txt_main += "\t//（1.7）【不变】开总中断\r\n"
                        + "\tENABLE_INTERRUPTS;\r\n"
                        + "\t//=======================（1）启动部分（结尾）=======================\r\n";
                    int tmp = 0;
                    txt_main += "\t//函数实现\n";//主程序函数代码的生成
                    ((GeneralIcon)IconGeneralArr[0]).CreateCode(ref txt_main, (GeneralIcon)IconGeneralArr[0], 1, true, ref tmp);
                    txt_main += "\r\n}\r\n";
                    //子函数代码的实现
                    temp = "";
                    string s = "";
                    if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null)
                        Globaldefine.FrmParent.ActivedrmGraphicFlow.m_FunDefine.Clear();
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        if (icon.Parent == null && icon.ModuleName == "定义函数")
                        {
                            string sTmp = icon.code.SubfunctionStart;
                            if (s.Contains(sTmp)) continue;
                            s += sTmp;
                            temp += sTmp;
                            icon.CreateCode(ref temp, icon, 1, true, ref iTemp);
                            temp += icon.code.SubfunctionEnd;

                            int index1 = icon.code.SubfunctionDeclare.IndexOf(' ');
                            int index2 = icon.code.SubfunctionDeclare.IndexOf('(');
                            string fun = icon.code.SubfunctionDeclare.Substring(index1 + 1, index2 - index1 - 1);
                            if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null
                                && !Globaldefine.FrmParent.ActivedrmGraphicFlow.m_FunDefine.Contains(fun))
                                Globaldefine.FrmParent.ActivedrmGraphicFlow.m_FunDefine.Add(fun);
                        }
                    }
                    txt_main += temp;

                    //[2021/1/31]PORTC_PORTD_IRQHandler为所有gpio事件控件公共中断服务例程
                    //直接添加在isr.c文件上
                    //isr.c文件
                    txt_isr =
                        "//=====================================================================\r\n"
                      + "//文件名称：isr.c\r\n"
                      + "//功能概要： 中断底层驱动构件源文件\r\n"
                      + "//版权所有：苏大arm技术中心(sumcu.suda.edu.cn)\r\n"
                      + "//更新记录：2017.01：1.0；2019.01：A.10\r\n"
                      + "//=====================================================================\r\n"
                      + "#include \"includes.h\"\r\n\r\n";

                    #region 目前的中断代码生成方式
                    //TODO 需要使用中断的控件只可能是事件控件
                    //所以只要遍历gpioEventControl、uartEventControl、timeEventControl即可
                    //而不需要遍历IconGeneralArr
                    temp = CreateInterruptCode(gpioEventControl, "EXTI15_10_IRQHandler");
                    temp += CreateInterruptCode(uartEventControl, "UART0_IRQHandler");
                    temp += CreateInterruptCode(UEcomEventControl, "UART_UE_Handler");
                    temp += CreateInterruptCode(timeEventControl, "SysTick_Handler");
                    #endregion

                    //增加生成模块中断代码

                    #region 过去的中断代码生成方式
                    //temp = "";
                    //s = "";
                    //if (gpioEventControl.Count > 0)
                    //{
                    //    txt_isr += "void PORTC_PORTD_IRQHandler(void)\r\n{\r\n"
                    //    + "\tDISABLE_INTERRUPTS;                       //关总中断\n";
                    //}

                    //foreach (GeneralIcon icon in IconGeneralArr)
                    //{
                    //    //去除判断icon.Parent == null && 
                    //    if (icon.ModuleName != "定义函数")
                    //    {
                    //        string sTmp = icon.code.InterruptServiceStart;
                    //        if (s.Contains(sTmp)) continue;
                    //        s += sTmp;
                    //        temp += sTmp;
                    //        icon.CreateCode(ref temp, icon, 1, true, ref iTemp);
                    //        temp += icon.code.InterruptServiceEnd;
                    //    }
                    //    //如果该控件是GPIO事件控件
                    //    if (gpioEventControl.Count > 0 && icon.GeneralIconType == GeneralIcon.TypeOfGeneralIcon.EventIcon
                    //        && (icon.ModuleName == "红外循迹" || icon.ModuleName == "人体红外" ||
                    //        icon.ModuleName == "碰撞检测" || icon.ModuleName == "触发式开关"))
                    //    {
                    //        //且是最后一个
                    //        int index = gpioEventControl.IndexOf(icon) + 1;
                    //        if (index == gpioEventControl.Count)
                    //        {
                    //            //添加中断代码结尾
                    //            //icon.code.InterruptServiceEnd += "\tENABLE_INTERRUPTS;       //开总中断\r\n}\r\n";
                    //            temp += "\tENABLE_INTERRUPTS;       //开总中断\r\n}\r\n";
                    //        }
                    //    }
                    //}
                    #endregion

                    txt_isr += temp;
                    if (isCrutch || isFridge)
                    {
                        if (isCrutch)
                            txt_isr +=
                                @"void PORTC_PORTD_IRQHandler(void)
{
    DISABLE_INTERRUPTS;                       //关总中断
    if (button_havePressed(J1))
    {
        btn_flag++;
        printf("+"\"按钮次数:%d\\n\""+@", btn_flag);
    }
    ENABLE_INTERRUPTS;       //开总中断
}
";
                        txt_isr += AddNBIsr();
                    }

                    txt_isr +=
                            //"\n\tENABLE_INTERRUPTS;                        //开总中断\r\n}" +
                         "/*\r\n 知识要素：\r\n"
                        + " 1.本文件中的中断处理函数调用的均是相关设备封装好的具体构件，在更换芯片\r\n"
                        + " 时，只需保证设备的构件接口一致，即可保证本文件的相关中断处理函数不做任何\r\n"
                        + " 更改，从而达到芯片无关性的要求。\r\n"
                        + " */\r\n";
                    //include.h文件
                    txt_includes =
                          "//======================================================================\r\n"
                        + "//文件名称：includes.h\r\n"
                        + "//功能概要：应用工程总头文件\r\n"
                        + "//版权所有：苏大arm技术中心(sumcu.suda.edu.cn)\r\n"
                        + "//版本更新：2017.2.1  V1.0， 2018.10.30 版本A.02\r\n"
                        + "//功能描述：（1）包含用到的构件；（2）宏常数定义；（3）自定义数据类型；\r\n"
                        + "//    （4）声明全局变量。\r\n"
                        + "//备    注：本文件共有两类代码，一类为【根据实际需要增删】，此类代码根据具体\r\n"
                        + "//    项目需求进行更改；另一类为【不动】，此类代码与具体项目无关，是通用的，\r\n"
                        + "//    无需根据具体项目进行更改。\r\n"
                        + "//======================================================================\r\n"
                        + "\r\n"
                        + "#ifndef _INCLUDES_H     //防止重复定义（开头）\r\n"
                        + "#define _INCLUDES_H\r\n\r\n";
                    txt_includes += "//（1）【根据实际需要增删】包含用到的构件\r\n"
                        + "#include \"user.h\"\r\n"
                        + "#include \"gcnb.h\"\r\n";

                    temp = "";
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        if (icon.code.HeadFile != "")
                        {
                            if (temp.Contains(icon.code.HeadFile))
                                continue;
                            temp += icon.code.HeadFile + "\r\n";
                        }
                    }
                    txt_includes += temp;
                    txt_includes += "//（2）【根据实际需要增删】全局使用的宏常数。命名规范见注1\r\n";
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        if (icon.code.MacroConstant != "")
                            txt_includes += icon.code.MacroConstant + "\r\n";
                    }
                    txt_includes += "//（3）【根据实际需要增删】自定义数据类型\r\n"
                        + "#pragma  pack(push,1)        //取消4字节对齐\r\n"
                        + "typedef struct FlashData\r\n"
                        + "{\r\n"
                        + "	uint8_t equipName[30];      //产品名称\r\n"
                        + "	uint8_t equipID[20];        //产品序列号\r\n"
                        + "	uint8_t equipType[20];      //产品型号\r\n"
                        + "	uint8_t vendor[30];         //生产厂家  100\r\n"
                        + "	uint8_t softVer[4];         //软件版本\r\n"
                        + "	uint64_t productTime;       //生产时间（64位时间戳）\r\n"
                        + "	uint8_t userName[20];       //用户名\r\n"
                        + "	uint8_t phone[11];          //手机号  43\r\n"
                        + "	uint8_t serverIP[15];       //服务器IP\r\n"
                        + "	uint8_t serverPort[5];      //服务器端口号\r\n"
                        + "	uint32_t sendFrequencySec;  //发送频率\r\n"
                        + "	uint32_t resetCount;        //复位次数\r\n"
                        + "	uint8_t  frameCmd[2];       //命令   30\r\n"
                        + "	uint8_t UE_SSID[32];        //接入点SSID\r\n"
                        + "	uint8_t UE_PSSWD[32];       //接入点密码\r\n"
                        + "}FlashData;\r\n"
                        + "typedef struct UserData\r\n"
                        + "{\r\n"
                        + "    uint8_t cmd[2];           //用户命令\r\n"
                        + "	uint16_t sn;              //帧号\r\n"
                        + "	uint8_t IMSI[15];         //IMSI号\r\n"
                        + "	uint8_t serverIP[15];     //服务器IP\r\n"
                        + "	uint8_t serverPort[5];    //服务器端口\r\n"
                        + "	uint64_t currentTime;     //发送时间（64位时间戳）\r\n"
                        + "	uint32_t resetCount;      //复位的次数\r\n"
                        + "	uint32_t sendFrequencySec;//发送时间间隔（秒）\r\n"
                        + "	uint8_t userName[20];     //用户名\r\n"
                        + "	uint8_t softVer[4];       //软件版本\r\n"
                        + "	uint8_t equipName[30];    //产品名称\r\n"
                        + "	uint8_t equipID[20];      //产品序列号\r\n"
                        + "	uint8_t equipType[20];    //产品类型\r\n"
                        + "	uint8_t vendor[30];       //生产厂家\r\n"
                        + "	int32_t mcuTemp;          //芯片温度\r\n"
                        + "	uint8_t surpBaseInfo[20]; //备注1\r\n"
                        + "	uint8_t phone[11];        //手机号\r\n"
                        + "	uint8_t IMEI[15];         //IMEI号\r\n"
                        + "	uint8_t signalPower;      //信号强度\r\n"
                        + "	uint16_t bright;          //光线亮度（光敏传感器A/D值）\r\n"
                        + "	uint16_t touchNum;        //触摸按键次数（TSI）\r\n"
                        + "	uint8_t surplusInfo[20];  //备注2\r\n"
                        + "	uint8_t lbs_location[25];\r\n"
                        + " uint64_t startTime;     //开始时间（64位时间戳）\r\n";
                    //[20210420] 使用智能拐杖或冰箱
                    if (isCrutch)
                    {
                        //[20210421] 处理智能拐杖、冰箱的userdata冲突问题
                        if (!AddNBCode("SmartCrutch"))
                        {
                            MessageBox.Show("文件已损坏！请重新安装！");
                            return;
                        }
                        txt_includes += " uint8_t fall_flag;      //跌倒标志\r\n";
                    }
                    else
                        DeleteNBCode("SmartCrutch");
                    if (isFridge)
                    {
                        if (!AddNBCode("refrigerator"))
                        {
                            MessageBox.Show("文件已损坏！请重新安装！");
                            return;
                        }
                        txt_includes += " int32_t ctlTemp;            //控制温度\r\n"
                                            + " int32_t in_sensorTemp;  //箱体内温度传感器温度\r\n"
                                            + " int32_t ex_sensorTemp;  //箱体外温度传感器温度\r\n";
                    }
                    else
                        DeleteNBCode("refrigerator");

                    //            int32_t ctlTemp;            //控制温度
                    //int32_t in_sensorTemp;  //箱体内温度传感器温度
                    //int32_t ex_sensorTemp;  //箱体外温度传感器温度

                    txt_includes += "}UserData;\r\n";
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        if (icon.code.CustomDataType != "")
                            txt_includes += icon.code.CustomDataType + "\r\n";
                    }
                    txt_includes += "#pragma  pack(pop)           //恢复4字节对齐\r\n";
                    txt_includes +=
                          "//（4）【根据实际需要增删】声明全局变量。命名规范见注2。\r\n"
                        + "//【不动】宏定义全局变量前缀G_VAR_PREFIX。实现原理见注3。\r\n"
                        + "#ifdef GLOBLE_VAR                      //GLOBLE_VAR在main.c文件中有宏定义\r\n"
                        + "  #define G_VAR_PREFIX                 //前缀G_VAR_PREFIX定义为空\r\n"
                        + "#else                                  //GLOBLE_VAR在非main.c文件中无定义\r\n"
                        + "  #define G_VAR_PREFIX extern         //前缀G_VAR_PREFIX定义为\"extern\"\r\n"
                        + "#endif\r\n\r\n"
                        + "//（在此增加全局变量）\r\n"
                        + "G_VAR_PREFIX uint16_t gcUserRecvLen;    //用户/配置数据帧长度\r\n"
                        + "G_VAR_PREFIX uint8_t  gCount;\r\n"
                        + "G_VAR_PREFIX vuint16_t gcRecvDCLen;\r\n"
                        + "G_VAR_PREFIX vuint8_t gcReccrc32[4];\r\n"
                        + "G_VAR_PREFIX uint16_t gcRecvLen;        //串口接收到的数据长度，为0时表示没有收到数据\r\n"
                        + "G_VAR_PREFIX UserData  gUserData;       //用户信息帧结构体\r\n"
                        + "G_VAR_PREFIX FlashData gFlashData;      //需要写入flash中的数据\r\n"
                        + "G_VAR_PREFIX uint64_t  gTimeSec;        //时间戳\r\n"
                        + "G_VAR_PREFIX vuint8_t   gTimeString[20]; \r\n"
                        + "G_VAR_PREFIX uint8_t   gcRecvBuf[2048];  //串口接收数据缓冲区\r\n"
                        + "G_VAR_PREFIX  uint8_t  gTime[3];        //时间数组\r\n"
                        + "G_VAR_PREFIX uint32_t  Retcount;             //用于记录进入中断次数\r\n"
                        + "G_VAR_PREFIX struct MAC gMac;        //时间数组\r\n"
                        + "G_VAR_PREFIX struct WiFiData gWiFiData;             //用于记录进入中断次数\r\n";
                    txt_includes += "const static FlashData flashInit[]=\r\n"
                        + "\t{\r\n"
                            + "\t\t{\r\n"
                            + "\t\t//012345678901234567890123456789  产品名称equipName[30]\r\n"
                            + "\t\t\"[金葫芦]WiFi终端UE模板\",\r\n"
                            + "\t\t//01234567890123456789  产品序列号equipID[20]\r\n"
                            + "\t\t\"SD-23-05      \",\r\n"
                            + "\t\t//01234567890123456789  产品型号equipType[20]\r\n"
                            + "\t\t\"AHL-STM32-WiFi-DX\",\r\n"
                            + "\t\t//012345678901234567890123456789    生产厂家vendor[30]\r\n"
                            + "\t\t\"SD-ARM 嵌入式人工智能与物联网\",\r\n"
                            + "\t\t//0123  软件版本softVer[4]\r\n"
                            + "\t\t\"0.40\",\r\n"
                            + "\t\t1683614384,\r\n"
                            + "\t\t//01234567890123456789  用户名userName[20]\r\n"
                            + "\t\t\"WiFi\",\r\n"
                            + "\t\t//01234567890  手机号phone[11]\r\n"
                            + "\t\t\"13000000000\",\r\n"
                            + "\t\t//012345678901234  服务器IPserverIP[15]\r\n"
                            + "\t\t\"116.62.63.164\",\r\n"
                            + "\t\t//01234 服务器端口号serverPort[5]\r\n"
                            + "\t\t\"34447\",\r\n"
                            + "\t\t//③用户存入flash的信息\r\n"
                            + "\t\t5,                          //发送频率\r\n"
                            + "\t\t0,                            //复位次数\r\n"
                            + "\t\t\"U0\",                        //命令\r\n"
                            + "\t\t\"oppo\",                      //命令\r\n"
                            + "\t\t\"123456xw\"                  //命令\r\n"
                            + "\t\t}\r\n"
                     + "\t};\r\n";

                    //[20210420]
                    if (isCrutch)
                        txt_includes += "G_VAR_PREFIX uint8_t  btn_flag;        //记录按钮按下的次数\r\n"
                        + "G_VAR_PREFIX uint32_t sendFrequencySec;   //时间间隔\r\n";
                    //G_VAR_PREFIX uint32_t sendFrequencySec;   //时间间隔
                    //G_VAR_PREFIX uint8_t  btn_flag;        //记录按钮按下的次数
                    if (isFridge)
                        txt_includes += "G_VAR_PREFIX uint32_t sendFrequencySec;   //时间间隔\r\n"
                            + "G_VAR_PREFIX int32_t ctlTemp;            //控制温度\r\n"
                            + "G_VAR_PREFIX float bodyTemp;  		//人体温度\r\n";
                    //G_VAR_PREFIX uint32_t sendFrequencySec;   //时间间隔
                    //G_VAR_PREFIX int32_t ctlTemp;            //控制温度
                    //G_VAR_PREFIX float bodyTemp;  		//人体温度


                    //+ "G_VAR_PREFIX  uint16_t  ray_Trace_flag;        //记录红外循迹左右检测情况的标记\r\n"
                    ;
                    temp = "";
                    foreach (GeneralIcon icon in IconGeneralArr)
                    {
                        if (icon.code.GlobalVariable != "")
                        {
                            string var_back = icon.code.GlobalVariable.Split(' ')[1];
                            string var = var_back.Split(';')[0];
                            if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null
                                //[20210508]去除全局变量后的;
                                && !Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys.Contains(var))
                                Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys.Add(var);
                            if (temp.Contains(icon.code.GlobalVariable))
                                continue;
                            temp += icon.code.GlobalVariable + ";\r\n";
                            
                        }
                    }
                    //if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null)
                    //    Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys.Clear();
                    string[] sVarS = temp.Split('\n');
                    temp = "";
                    foreach(string ss in sVarS)
                    {
                        //[20210508]
                        if (ss == "" || ss == "\r" || ss == "\r\n" || ss == " " || ss == ";\r") continue;
                        temp += "G_VAR_PREFIX " + ss + "\n";
                        int index1 = ss.IndexOf(' ');
                        int index2;
                        if (ss.Contains("["))
                            index2 = ss.IndexOf('[');
                        else
                            index2 = ss.IndexOf(';');
                        var sss = ss.Substring(index1 + 1, index2 - index1 - 1);
                        //if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null
                        //    && !Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys.Contains(sss))
                        //    Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys.Add(sss);
                    }
                    //if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null
                    //        && !Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys.Contains("ray_Trace_flag"))
                    //{
                    //    Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys.Add("ray_Trace_flag");
                    //}
                    txt_includes += temp;
                    txt_includes += "#endif\r\n"
                        + "/*\r\n"
                        + "知识要素：\r\n"
                        + " （1）本文件共有两类代码，一类为【根据实际需要增删】，此类代码根据具体\r\n"
                        + " 项目需求进行更改；另一类为【不动】，此类代码与具体项目无关，是通用的，\r\n"
                        + " 无需根据具体项目进行更改。\r\n"
                        + " （2）全局变量一处声明多处使用处理方法代码段是为了解决全局变量重复声明\r\n"
                        + " 的问题，宏GLOBLE_VAR仅在main.c中声明，所以只有在main.c中包含\r\n"
                        + " 本头文件时才会声明全局变量，在其他文件中包含本文件时，编译时，就会自动加\r\n"
                        + " 上前缀extern，表明是main函数中声明的全局变量，该文件中直接使用。\r\n"
                        + " （3）声明全局变量时，一律加前缀G_VAR_PREFIX，并只在本文件\r\n"
                        + " 的“全局变量声明处”声明， 仅在此一次声明即可。 全局变量命名一律以g开头，\r\n"
                        + " 尽可能保证全工程内唯一性，并且一定要注明其含义（声明时不准赋值）。\r\n"
                        + " （4）全局使用的宏常数，使用全大写\r\n"
                        + " */\r\n";

                }
                Globaldefine.FrmParent.CodeOfForm.text_main.Text = txt_main;
                Globaldefine.FrmParent.CodeOfForm.text_main.Refresh();
                Globaldefine.FrmParent.CodeOfForm.text_isr.Text = txt_isr;
                Globaldefine.FrmParent.CodeOfForm.text_isr.Refresh();
                Globaldefine.FrmParent.CodeOfForm.text_includes.Text = txt_includes;
                Globaldefine.FrmParent.CodeOfForm.text_includes.Refresh();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        public string AddNBIsr()
        {
            return @"void User_SysFun(uint8_t ch);
void SecAdd1(uint8_t *p);
//======================================================================
//函数名称：UART_UE_Handler
//参数说明：无
//函数返回：无
//功能概要：串口UE接收中断服务程序
//======================================================================
void UART_UE_Handler(void)
{
	uint8_t ch;
	uint8_t flag;
	DISABLE_INTERRUPTS;      //关总中断
	//-------------------------------
    //接收一个字节
	ch = uart_re1(UART_UE, &flag);   //调用接收一个字节的函数，清接收中断位

	//串口数据接收失败，退出
	if(!flag) goto UART_UE_IRQHandler_Exit;
	//gcRecvLen为0，表示上一帧数据处理接收，可重新接收数据
	if(gcRecvLen == 0)                           //组帧
		uecom_interrupt(ch,&gcRecvLen,gcRecvBuf);  
	else                                         //丢弃
		goto UART_UE_IRQHandler_Exit;
	//未接收到服务器发来的数据，退出
	if(gcRecvLen == 0) goto UART_UE_IRQHandler_Exit;
    //已经收到一帧字节数为gcRecvLen，在gcRecvBuf中，由main.c处理
UART_UE_IRQHandler_Exit:
	//-------------------------------
	ENABLE_INTERRUPTS;       //开总中断
}

//======================================================================
//程序名称：UART_User_Handler
//触发条件：UART_User串口收到一个字节触发
//备    注：进入本程序后，可使用uart_get_re_int函数可再进行中断标志判断
//          （1-有UART接收中断，0-没有UART接收中断）
//======================================================================
void UART_User_Handler(void)
{
	 //（1）变量声明
    uint8_t flag,ch;
    DISABLE_INTERRUPTS;      //关总中断
    //（2）未触发串口接收中断，退出
    if(!uart_get_re_int(UART_User)) goto UART_User_Handler_EXIT;
    //（3）收到一个字节，读出该字节数据
    ch = uart_re1(UART_User,&flag);        //调用接收一个字节的函数
    if(!flag) goto UART_User_Handler_EXIT; //实际未收到数据，退出
  //（4）以下代码根据是否使用模板提供的User串口通信帧结构，及是否利用User串口
    //     进行带有设备序列号的进行程序更新而选择
    //（4.1）【自行组帧使用（开始)】
        uart_send1(UART_User,ch);     //例如，收到一个字节回发一个字节
       //    【自行组帧使用（结束)】
    //（4.2）【使用模板提供的User串口通信帧结构（开始)】
    /*
       User_SysFun(ch);          //利用User串口进行程序更新
       if (gcRecvLen == 0) goto UART_User_Handler_EXIT; 
       //至此，不仅收到完整帧，且序号比较也一致，可以根据命令字节gcRecvBuf[16]进行编程
       switch(gcRecvBuf[16])  //帧标识
       {
           case 1:  //0之外的数据，自身命令
           break;
           default:
           break;
        }
        gcRecvLen = 0;   //帧已经使用完毕，下次若收到一个字节，可以继续组帧
        //【使用模板提供的User串口通信帧结构（结束)】
     */
    //（5）【公共退出区】
UART_User_Handler_EXIT:
    ENABLE_INTERRUPTS;//开总中断
}
//=====================================================================
//函数名称：TIMER_USER_Handler（TPM1定时器中断处理程序）
//参数说明：无
//函数返回：无
//功能概要：（1）每20ms中断触发本程序一次；（2）达到一秒时，调用秒+1
//           程序，计算“时、分、秒”
//特别提示：（1）使用全局变量字节型数组gTime[3]，分别存储“时、分、秒”
//        （2）注意其中静态变量的使用
//=====================================================================
void TIMER_USER_Handler(void)
{
	DISABLE_INTERRUPTS;                        //关总中断
	//------------------------------------------------------------------
	//（在此处增加功能）
	//申请一个静态的计数器值
	static vuint8_t TimerCount = 0;
	//获取当前时钟溢出标志位
	if(timer_get_int(TIMER_USER))
	{
		TimerCount++;           //计数器累加

		if (TimerCount >= 50)
		{
			Retcount++;
			if(Retcount>43200)
				NVIC_SystemReset();
			TimerCount = 0;    //时钟计数器清零
			SecAdd1((uint8_t *)(gTimeString));    //时间显示累加
		}
	
		timer_clear_int(TIMER_USER);    //清时钟溢出标志位
	}
	//------------------------------------------------------------------
	ENABLE_INTERRUPTS;                        //开总中断

}


//内部函数
void User_SysFun(uint8_t ch)
{
    //（1）收到的一个字节参与组帧
    if(gcRecvLen == 0)  gcRecvLen =useremuart_frame(ch,(uint8_t*)gcRecvBuf);
    //（2）字节进入组帧后，判断gcRecvLen=0？若为0，表示组帧尚未完成，
    //     下次收到一个字节，再继续组帧
    if(gcRecvLen == 0) goto User_SysFun_Exit;
    //（3）至此，gcRecvLen≠0,表示组帧完成，gcRecvLen为帧的长度,校验序列号后（与
    //     根据Flash中倒数一扇区开始的16字节进行比较）
    //     gcRecvBuf[16]进行跳转
    if(strncmp((char *)(gcRecvBuf),(char *)((MCU_SECTOR_NUM-1)*MCU_SECTORSIZE+
       MCU_FLASH_ADDR_START),16) != 0)
    {
        gcRecvLen = 0;         //恢复接收状态
        goto User_SysFun_Exit;
    }
    //（4）至此，不仅收到完整帧，且序号比较也一致， 根据命令字节gcRecvBuf[16]进行跳转
    //若为User串口程序更新命令，则进行程序更新
    switch(gcRecvBuf[16])  //帧标识
    {
        case 0:
            SYSTEM_FUNCTION((uint8_t *)(gcRecvBuf+17));
            gcRecvLen = 0;         //恢复接收状态
        break;
        default:
        break;
    }
User_SysFun_Exit:
    return;
}
//===========================================================================
//函数名称：SecAdd1
//函数返回：无
//参数说明：*p:为指向一个时分秒数组p[3]
//功能概要：秒单元+1，并处理时分单元（00:00:00-23:59:59)
//2020-01-01 00:00:00 19位ASCII码
//===========================================================================
void SecAdd1(uint8_t *p)
{
    *(p+18)+=1;             //秒个位
    if((*(p+18)>0x39))     //秒个位满十
    {
      *(p+18)=0x30;
      *(p+17)+=1;          //秒十位
      if((*(p+17)>0x35))   //秒十位=6，分个位+1
      {
        *(p+18)=0x30;
        *(p+17)=0x30;
        *(p+15)+=1;    
        if((*(p+15)>0x39))  //分个位满十，分个位，秒十位，个位归0，分十位+1
        {
          *(p+18)=0x30;     
          *(p+17)=0x30;
          *(p+15)=0x30;  
          *(p+14)+=1;  
          if((*(p+14)>0x35))   //分十位=6，时个位+1，分秒归0
          {
            *(p+18)=0x30;     
            *(p+17)=0x30;
            *(p+15)=0x30;  
            *(p+14)=0x30;  
            *(p+12)+=1;         
            if((*(p+12)>0x39))  //时个位满十，时十位加1，分秒归0
            {
              if( (*(p+11))<0x32)
              {
                *(p+18)=0x30;     
                *(p+17)=0x30;
                *(p+15)=0x30;  
                *(p+14)=0x30;
                *(p+12)=0x30;  
                *(p+11)+=1;  
              }


            }
            
          }
        }
      
      }
    }
}
";
        }


        /// <summary>
        /// 【20210421】
        /// 导入或移除NB对应的代码（.c和.h文件）
        /// 解决头文件互包导致未使用文件编译的问题
        /// </summary>
        /// <param name="filename">.c和.h文件名</param>
        /// <returns></returns>
        public bool AddNBCode(string filename)
        {
            //NB文件的源文件和目标文件前面的路径
            string srcfilepath = Path.Combine(Globaldefine.exePath, "Project\\AHL-KL36-V3.6\\KDS");
            string desfilepath = Path.Combine(Globaldefine.exePath, "Project\\AHL-KL36-V3.6\\KDS\\Source\\05_UserBoard");
            //[20210421]加入.h和.c E:\03-图形化\Easily-V1.2-202104021-SmartGZ-NB\bin\Debug\
            string src_c = Path.Combine(srcfilepath, filename + ".c");
            string src_h = Path.Combine(srcfilepath, filename + ".h");
            string des_c = Path.Combine(desfilepath, filename + ".c");
            string des_h = Path.Combine(desfilepath, filename + ".h");
            //存在NB文件则导入
            if (File.Exists(src_c) && File.Exists(src_h))
            {
                //若已存在文件 就不需要重复拷贝
                if (!File.Exists(des_c))
                    File.Copy(src_c, des_c);
                if (!File.Exists(des_h))
                    File.Copy(src_h, des_h);
                return true;
            }
            //文件不存在 返回给上一层处理
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 若不存在对应的NB模块
        /// 就删除对应的.c和.h文件
        /// </summary>
        /// <param name="filename"></param>
        public void DeleteNBCode(string filename)
        {
            //NB文件的源文件和目标文件前面的路径
            string desfilepath = Path.Combine(Globaldefine.exePath, "Project\\AHL-KL36-V3.6\\KDS\\Source\\05_UserBoard");
            //[20210421]加入.h和.c E:\03-图形化\Easily-V1.2-202104021-SmartGZ-NB\bin\Debug\
            string des_c = Path.Combine(desfilepath, filename + ".c");
            string des_h = Path.Combine(desfilepath, filename + ".h");
            //若存在文件 则删除
            if (File.Exists(des_c))
                File.Delete(des_c);
            if (File.Exists(des_h))
                File.Delete(des_h);
        }

        /// <summary>
        /// TODO CreateInterruptCode
        /// </summary>
        /// <param name="eventControl">需要处理的事件控件列表</param>
        /// <param name="inteFuncName">中断函数名</param>
        /// <returns></returns>
        private string CreateInterruptCode(ArrayList eventControl,string inteFuncName)
        {
            string inteCode = "";
            int count = 0;
            //如果该事件控件列表不为空 则开始处理
            if (eventControl.Count > 0)
            {
                //加入函数头PORTC_PORTD_IRQHandler
                inteCode += "void "+ inteFuncName + "(void)\r\n{\r\n"
                + "\tDISABLE_INTERRUPTS;                       //关总中断\n";
                string s = "";
                //遍历事件控件列表
                foreach (GeneralIcon icon in eventControl)
                {
                    string sTmp = icon.code.InterruptServiceStart;
                    //[20210511]处理定时器不产生代码的错误，InterruptServiceStart为""，这里会跳过处理
                    if (sTmp!=""&&s.Contains(sTmp)) continue;
                    s += sTmp;
                    inteCode += sTmp;
                    icon.CreateCode(ref inteCode, icon, 1, true, ref count);
                    inteCode += icon.code.InterruptServiceEnd;
                }
                //结束后加入函数尾
                inteCode += "\tENABLE_INTERRUPTS;       //开总中断\r\n}\r\n";
            }
            return inteCode;
        }

        /// <summary>
        /// 根据传入的字符流，复原工程，即打开工程
        /// </summary>
        /// <param name="path">工程路径</param>
        /// <returns>0：普通模式 1：高级模式</returns>
        public int OpenPro(string path)
        {
            int i;
            //string strLine = string.Empty;

            for (i = 0; i < IconGeneralArr.Count; i++)
            {
                ((GeneralIcon)IconGeneralArr[i]).Dispose();
            }
            
            IconGeneralArr.Clear();

            XDocument xProject = XDocument.Load(path);
            //[2021/1/30] 获取保存的配置终端的信息
            XElement xHard_connect = xProject.Element("project").Element("hard_connect");
            hard_Connect.J1 = xHard_connect.Element("J1").Value;
            hard_Connect.J2 = xHard_connect.Element("J2").Value;
            hard_Connect.J3 = xHard_connect.Element("J3").Value;
            hard_Connect.J4 = xHard_connect.Element("J4").Value;
            hard_Connect.J5 = xHard_connect.Element("J5").Value;
            hard_Connect.J6 = xHard_connect.Element("J6").Value;
            hard_Connect.J7 = xHard_connect.Element("J7").Value;
            hard_Connect.J8 = xHard_connect.Element("J8").Value;
            //[2021/1/31]读取control_Cnt
            XElement xcontrol_Cnt = xProject.Element("project").Element("control_Cnt");
            //去除字符串头和尾的括号以方便分割
            string control_cnt = xcontrol_Cnt.Value.Substring(1,xcontrol_Cnt.Value.Length-2);
            //以"]["为分隔符，分割字符串
            string[] control_cnts = control_cnt.Split(new string[] { "][" },StringSplitOptions.RemoveEmptyEntries);
            //以,为分隔符取出key和value保存在control_Cnt中
            foreach (string item in control_cnts)
            {
                string[] res = item.Split(',');
                Globaldefine.loadConfig.control_Cnt[res[0]] = Int32.Parse(res[1]);
            }
            XElement xCode = xProject.Element("project").Element("code");      //获取保存的高级模式下的代码          
            XElement xMain = xProject.Element("project").Element("source");    //获取保存的图形化控件信息
            IEnumerable<XElement> xControl = xMain.Elements("control");
            //还原设置
            foreach(XElement x in xControl)
            {
                GeneralIcon zx = new GeneralIcon
                {
                    GeneralIconType = (GeneralIcon.TypeOfGeneralIcon)(Convert.ToInt16(x.Element("type").Value)),
                    ModuleName = x.Element("module_name").Value,
                    //[2021/1/30 添加IconName属性读取]
                    IconName = x.Element("icon_name").Value,

                    IconDbNum = Convert.ToInt16(x.Element("index_db").Value),
                    IconLeftDotNum = Convert.ToInt16(x.Element("left_dot").Value),
                    IconTopDotNum = Convert.ToInt16(x.Element("up_dot").Value),
                    IconArrNum = Convert.ToInt16(x.Element("index_array").Value),
                    IconFuncType = Convert.ToInt16(x.Element("func_type").Value)
                };
                zx.code.Comment = x.Element("code_comment").Value;
                zx.code.InsertCode = x.Element("insert_code").Value;
                zx.code.Save = x.Element("save").Value;
                if(x.Element("father").Attribute("exist").Value == "true")
                {
                    zx.ParentType = (GeneralIcon.LinkIconType)(Convert.ToInt16(x.Element("father").Element("type").Value));
                    zx.ParentIconArrNum = (Convert.ToInt16(x.Element("father").Element("index").Value));
                }
                if(x.Element("son").Attribute("exist").Value == "true")
                {
                    zx.ChildType = (GeneralIcon.LinkIconType)(Convert.ToInt16(x.Element("son").Element("type").Value));
                    zx.ChildIconArrNum = Convert.ToInt16(x.Element("son").Element("index").Value);
                    zx.ChildDotX = Convert.ToInt16(x.Element("son").Element("dotX").Value);
                    zx.ChildDotY = Convert.ToInt16(x.Element("son").Element("dotY").Value);
                }
               
                IconGeneralArr.Add(zx);
                //TODO 人工判断是不是GPIO事件控件
                if(zx.GeneralIconType==GeneralIcon.TypeOfGeneralIcon.EventIcon
                    &&(zx.ModuleName== "红外循迹"|| zx.ModuleName == "人体红外" || 
                    zx.ModuleName == "碰撞检测" || zx.ModuleName == "触发式开关"))
                {
                    gpioEventControl.Add(zx);
                }
                if (zx.GeneralIconType == GeneralIcon.TypeOfGeneralIcon.EventIcon
                    && (zx.ModuleName == "接收到串口数据"))
                {
                    uartEventControl.Add(zx);
                }
                if (zx.GeneralIconType == GeneralIcon.TypeOfGeneralIcon.EventIcon
                    && (zx.ModuleName == "接收到WIFI数据"))
                {
                    UEcomEventControl.Add(zx);
                }
                if (zx.GeneralIconType == GeneralIcon.TypeOfGeneralIcon.EventIcon
                    && (zx.ModuleName == "定时器时间到"))
                {
                    timeEventControl.Add(zx);
                }
            }

            //置通用控件的父子关系
            for (i = 0; i < IconGeneralArr.Count; i++)
            {
                if (((GeneralIcon)IconGeneralArr[i]).ParentType != GeneralIcon.LinkIconType.NULL)
                {
                     ((GeneralIcon)IconGeneralArr[i]).Parent = (GeneralIcon)IconGeneralArr[((GeneralIcon)IconGeneralArr[i]).ParentIconArrNum];
                }
                if (((GeneralIcon)IconGeneralArr[i]).ChildType != GeneralIcon.LinkIconType.NULL)
                {
                     ((GeneralIcon)IconGeneralArr[i]).Child = (GeneralIcon)IconGeneralArr[((GeneralIcon)IconGeneralArr[i]).ChildIconArrNum];
                }
            }

            //创建控件图标
            //通用控件图标
            for (i = 0; i < IconGeneralArr.Count; i++)
            {
                if (((GeneralIcon)IconGeneralArr[i]).IconFuncType == 1)//主程序类型
                {
                    ((GeneralIcon)IconGeneralArr[i]).CreateGeneralImage(((GeneralIcon)IconGeneralArr[i]).GeneralIconType, ((GeneralIcon)IconGeneralArr[i]).ModuleName, ((GeneralIcon)IconGeneralArr[i]).IconName,((GeneralIcon)IconGeneralArr[i]).IconLeftDotNum, ((GeneralIcon)IconGeneralArr[i]).IconTopDotNum, this, false);
                }
                else
                {
                    ((GeneralIcon)IconGeneralArr[i]).CreateGeneralImage(((GeneralIcon)IconGeneralArr[i]).GeneralIconType, ((GeneralIcon)IconGeneralArr[i]).ModuleName, ((GeneralIcon)IconGeneralArr[i]).IconName, ((GeneralIcon)IconGeneralArr[i]).IconLeftDotNum, ((GeneralIcon)IconGeneralArr[i]).IconTopDotNum, this, true);
                }
            }
            //如果该工程在高级模式下编辑过，则恢复保存的代码
            if (xCode.Element("isAdvanceMode").Value == "true")
            {
                Globaldefine.FrmParent.CodeOfForm.text_main.Text = xCode.Element("main.c").Value;
                Globaldefine.FrmParent.CodeOfForm.text_includes.Text = xCode.Element("includes.h").Value;
                Globaldefine.FrmParent.CodeOfForm.text_isr.Text = xCode.Element("isr.c").Value;
                return 1;
            }
            else
                return 0;
            
        }

        /// <summary>将工程保存到prj中，采用xml文件格式[20181126]</summary>
        public void SavePro(string path)
        {
            int i;
            XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XComment("存储Easily工程信息"),
                new XElement("project", new XElement("AppVersion", "V0.2")));
            //[2021/1/30] 添加hard_connect保存
            xdoc.Element("project").Add(new XElement("hard_connect", 
                new XElement("J1", hard_Connect.J1), new XElement("J2", hard_Connect.J2), new XElement("J3", hard_Connect.J3),
                new XElement("J4", hard_Connect.J4), new XElement("J5", hard_Connect.J5), new XElement("J6", hard_Connect.J6),
                new XElement("J7", hard_Connect.J7), new XElement("J8", hard_Connect.J8)));
            //[2021/1/31]添加control_Cnt
            xdoc.Element("project").Add(new XElement("control_Cnt", Globaldefine.loadConfig.control_Cnt));
            //存储main控件树
            xdoc.Element("project").Add(new XElement("source", new XAttribute("name", "main")));
            xdoc.Element("project").Add(new XElement("code", new XAttribute("name", "temp")));
            
            XElement xSource = xdoc.Element("project").Element("source");
            XElement xTemp = xdoc.Element("project").Element("code");
            string father = "false",son="false";
            //保存窗体中存在的通用控件的信息
            for (i = 0; i < IconGeneralArr.Count; i++)
            {
                if (((GeneralIcon)IconGeneralArr[i]).Parent != null)
                    father = "true";
                if (((GeneralIcon)IconGeneralArr[i]).Child != null)
                    son = "true";
                xSource.Add(new XElement("control", new XAttribute("id", i.ToString()),
                    new XElement("type",((int)(((GeneralIcon)IconGeneralArr[i]).GeneralIconType)).ToString()),
                    //[2021/1/30 添加iconname属性]
                    new XElement("module_name",((GeneralIcon)IconGeneralArr[i]).ModuleName.ToString()),
                    new XElement("icon_name", ((GeneralIcon)IconGeneralArr[i]).IconName.ToString()),
                    new XElement("index_db",((GeneralIcon)IconGeneralArr[i]).IconDbNum.ToString()),
                    new XElement("left_dot",((GeneralIcon)IconGeneralArr[i]).IconLeftDotNum.ToString()),
                    new XElement("up_dot",((GeneralIcon)IconGeneralArr[i]).IconTopDotNum.ToString()),
                    new XElement("index_array",((GeneralIcon)IconGeneralArr[i]).IconArrNum.ToString()),
                    new XElement("func_type",((GeneralIcon)IconGeneralArr[i]).IconFuncType.ToString()),
                    new XElement("code_comment", ((GeneralIcon)IconGeneralArr[i]).code.Comment.ToString()),
                    new XElement("insert_code", ((GeneralIcon)IconGeneralArr[i]).code.InsertCode.ToString()),
                    new XElement("save", ((GeneralIcon)IconGeneralArr[i]).code.Save.ToString()),
                    new XElement("father",new XAttribute("exist",father),
                        new XElement("type",((int)(((GeneralIcon)IconGeneralArr[i]).ParentType)).ToString()),
                        new XElement("index",((GeneralIcon)IconGeneralArr[i]).ParentIconArrNum.ToString())
                        ),
                    new XElement("son",new XAttribute("exist",son),
                        new XElement("type",((int)(((GeneralIcon)IconGeneralArr[i]).ChildType)).ToString()),
                        new XElement("index",((GeneralIcon)IconGeneralArr[i]).ChildIconArrNum.ToString()),
                        new XElement("dotX",((GeneralIcon)IconGeneralArr[i]).ChildDotX.ToString()),
                        new XElement("dotY",((GeneralIcon)IconGeneralArr[i]).ChildDotY.ToString())
                        )
                    ));
                
                father = son = "false"; 
            }
            //高级模式下保存编辑的代码
            xTemp.Add(new XElement("isAdvanceMode", Globaldefine.FrmParent.IsAdvanceMode),
                        new XElement("main.c", Globaldefine.FrmParent.CodeOfForm.text_main.Text),
                        new XElement("isr.c", Globaldefine.FrmParent.CodeOfForm.text_isr.Text),
                        new XElement("includes.h", Globaldefine.FrmParent.CodeOfForm.text_includes.Text)
                );        
            xdoc.Save(path);
        }
//=============================================================================
        /// <summary>删除图标 2015-5-16 【GZF】</summary>
        public void DeleteIcon()
        {
            try
            {
                //单个控件图标选中删除的情况
                if (this.SelectedIcon != null)
                {
                    //[2021/1/31]删除控件时control_Cnt对应控件减一,前提是控件数量大于0也就是有该控件
                    if (Globaldefine.loadConfig.control_Cnt.ContainsKey(this.SelectedIcon.ModuleName))
                        if(Globaldefine.loadConfig.control_Cnt[this.SelectedIcon.ModuleName]>0)
                            Globaldefine.loadConfig.control_Cnt[this.SelectedIcon.ModuleName]--;
                    //删除该外设对应局部变量 前提时它存在局部变量
                    if (m_Sensor_VariableLocal.ContainsKey(SelectedIcon.IconName))
                        m_Sensor_VariableLocal.Remove(SelectedIcon.IconName);
                    //if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null)
                    //{
                    //    for (int num = 0; num < Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal.Count; num++)
                    //    {
                    //        if (Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal[num].ToString().Contains(insertVar.Substring(3)))
                    //            Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal.RemoveAt(j);
                    //    }
                    //    Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal.Add(insertVar);
                    //}
                    if ((this.SelectedIconType != LineLinkIconType.NULL) && (this.SelectedIconNum != -1))
                    {
                        int i;
                        GeneralIcon  tempIcon;
                        GeneralIcon LasttempIcon;   //流程模块中最后一个被删除的节点

                        //判断删除的控件的类型
                        switch (this.SelectedIconType)
                        {
                            case LineLinkIconType.GeneralIcon:
                                if (SelectedIconNum != 0)
                                {
                                    //========删除对应的模块变量===========================/*
                                    if (((GeneralIcon)IconGeneralArr[SelectedIconNum]).code.InsertCode != "")
                                    {
                                        if (((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName == "计数循环")
                                        {
                                            //[2021/4/28]这里的处理是为了删除以前使用的变量 但是现在不需要这样
                                            //因为所有的变量都在外面定义 计数循环选择即可
                                            //int pos = ((GeneralIcon)IconGeneralArr[SelectedIconNum]).code.InsertCode.IndexOf('C') + 1;
                                            //int end = ((GeneralIcon)IconGeneralArr[SelectedIconNum]).code.InsertCode.IndexOf('=', pos);
                                            //string v = ((GeneralIcon)IconGeneralArr[SelectedIconNum]).code.InsertCode.Substring(pos, end - pos);

                                            //for (i = 0; i < ForVariable.Count; i++)//查找循环变量，并删除
                                            //{
                                            //    if (ForVariable[i].ToString() == v)
                                            //    {
                                            //        ForVariable.RemoveAt(i);
                                            //        break;
                                            //    }
                                            //}
                                        }
                                     
                                    }
                                    //===暂时不删除对应的模块变量！！因删除一个控件，删除同类控件的所有变量会出问题（该控件多处使用时）

                                    // 如果选中删除的节点流程关联节点时不响应删除，只能通用节点和流程头节点可以删除---排除一下节点的情况
                                    if ((((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName != "单分支End") &&
                                        (((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName != "双分支End1") &&
                                        (((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName != "双分支End2") &&
                                        (((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName != "计数循环End") &&
                                        (((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName != "条件循环End"))
                                    {
                                         //流程控件头节点情况
                                        if ((((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName == "单分支") ||
                                            (((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName == "双分支") ||
                                            (((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName == "计数循环")||
                                            (((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName == "条件循环"))
                                        {   
                                            //移除一个节点数组下标编号会发生变化，后续节点数组编号自动减一 
                                            if (((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName == "双分支")
                                                LasttempIcon = (GeneralIcon)IconGeneralArr[SelectedIconNum+2];  //确定最后一个被删除的节点
                                            else
                                                LasttempIcon = (GeneralIcon)IconGeneralArr[SelectedIconNum + 1];

                                            //((GeneralIcon)IconGeneralArr[SelectedIconNum]).ResetParent((GeneralIcon)IconGeneralArr[SelectedIconNum]);
                                            //重置对应的父节点和子节点===让前后相连20160328=====
                                            ((GeneralIcon)IconGeneralArr[SelectedIconNum]).DelLcReConnect((GeneralIcon)IconGeneralArr[SelectedIconNum], LasttempIcon);

                                            tempIcon = (GeneralIcon)IconGeneralArr[SelectedIconNum];
                                            while (tempIcon != LasttempIcon)
                                            {
                                                SelectedIconNum = tempIcon.IconArrNum;
                                                tempIcon =(GeneralIcon) tempIcon.Child;

                                                //重置对应的父节点和子节点（）
                                                //((GeneralIcon)IconGeneralArr[SelectedIconNum]).ResetChild((GeneralIcon)IconGeneralArr[SelectedIconNum]);
                                                //((GeneralIcon)IconGeneralArr[SelectedIconNum]).ResetParent((GeneralIcon)IconGeneralArr[SelectedIconNum]);

                                                // 移除节点控件上的小图标
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).IconPicBox);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).MoveToIconPicBox);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).InPic1);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).InPic2);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).OutPic1);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).OutPic2);
                                                for (i = SelectedIconNum + 1; i < IconGeneralArr.Count; i++)
                                                {    //修改其他控件在数组中的下标位置
                                                    ((GeneralIcon)IconGeneralArr[i]).IconArrNum--;
                                                }
                                                gpioEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                                uartEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                                timeEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                                IconGeneralArr.RemoveAt(SelectedIconNum); //移除选中的节点

                                            }// while
                                            if (tempIcon == LasttempIcon)
                                            {
                                                SelectedIconNum = tempIcon.IconArrNum;
                                                
                                                //重置对应的父节点和子节点（）
                                               // ((GeneralIcon)IconGeneralArr[SelectedIconNum]).ResetChild((GeneralIcon)IconGeneralArr[SelectedIconNum]);
                                                //((GeneralIcon)IconGeneralArr[SelectedIconNum]).ResetParent((GeneralIcon)IconGeneralArr[SelectedIconNum]);

                                                // 移除节点控件上的小图标
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).IconPicBox);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).MoveToIconPicBox);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).InPic1);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).InPic2);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).OutPic1);
                                                this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).OutPic2);
                                                for (i = SelectedIconNum + 1; i < IconGeneralArr.Count; i++)
                                                {    //修改其他控件在数组中的下标位置
                                                    ((GeneralIcon)IconGeneralArr[i]).IconArrNum--;
                                                }
                                                gpioEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                                uartEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                                UEcomEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                                timeEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                                IconGeneralArr.RemoveAt(SelectedIconNum); //移除选中的节点


                                            }
                                         }

                                        else //非流程控件节点情况
                                        {
                                            //重置对应的父节点和子节点（）
                                           //((GeneralIcon)IconGeneralArr[SelectedIconNum]).ResetChild((GeneralIcon)IconGeneralArr[SelectedIconNum]);
                                          //  ((GeneralIcon)IconGeneralArr[SelectedIconNum]).ResetParent((GeneralIcon)IconGeneralArr[SelectedIconNum]);
                                       
                                            //重置对应的父节点和子节点===让前后相连20160328=====
                                            ((GeneralIcon)IconGeneralArr[SelectedIconNum]).DelReConnect((GeneralIcon)IconGeneralArr[SelectedIconNum]);
                                            
                                            // 移除节点控件上的小图标
                                            this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).IconPicBox);
                                            this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).MoveToIconPicBox);
                                            this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).InPic1);
                                            this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).InPic2);
                                            this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).OutPic1);
                                            this.Controls.Remove(((GeneralIcon)IconGeneralArr[SelectedIconNum]).OutPic2);
                                            for (i = SelectedIconNum + 1; i < IconGeneralArr.Count; i++)
                                            {    //修改其他控件在数组中的下标位置
                                                ((GeneralIcon)IconGeneralArr[i]).IconArrNum--;
                                            }
                                            gpioEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                            uartEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                            UEcomEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                            timeEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                            IconGeneralArr.RemoveAt(SelectedIconNum); //移除选中的节点

                                        }
                                        for (i = 0; i < IconGeneralArr.Count; i++)
                                        {
                                            SetRelation((GeneralIcon)IconGeneralArr[i]);//20151207调整连接控件，使其排成一列。
                                        }
                                        
                                    } 
                                 }
                                break;
                            default:
                                break;
                        }
                        this.SelectedIconType = LineLinkIconType.NULL;
                        SelectedIconNum = -1;
                        for (i = 0; i < IconGeneralArr.Count; i++)
                        {
                            if (((GeneralIcon)(IconGeneralArr[i])).Parent == null)
                            {
                                ((GeneralIcon)(IconGeneralArr[i])).ResettingRelation((GeneralIcon)(IconGeneralArr[i]));
                            }
                        }
                    }
                }
                //多个控件图标选中删除的情况
                int j, k;
                for (j = 0; j < SelectedIconArr.Count; j++)
                {
                    //[2021/1/31]删除控件时control_Cnt对应控件减一,前提是控件数量大于0也就是有该控件
                    if (Globaldefine.loadConfig.control_Cnt.ContainsKey(((Icon)SelectedIconArr[j]).ModuleName))
                        if (Globaldefine.loadConfig.control_Cnt[((Icon)SelectedIconArr[j]).ModuleName] > 0)
                            Globaldefine.loadConfig.control_Cnt[((Icon)SelectedIconArr[j]).ModuleName]--;
                    //判断删除的控件的类型
                    switch (((Icon)SelectedIconArr[j]).IconType)
                    {
                        case Easily.Icon.LinkIconType.GeneralIcon:
                            if (((GeneralIcon)SelectedIconArr[j]).IconArrNum != 0)
                            {
                                if (((GeneralIcon)SelectedIconArr[j]).notePic.Visible)
                                {
                                    ((GeneralIcon)SelectedIconArr[j]).notePic.Visible = false;
                                    this.Controls.Remove(((GeneralIcon)SelectedIconArr[j]).notePic);
                                }
                                ((GeneralIcon)SelectedIconArr[j]).ResetChild((GeneralIcon)SelectedIconArr[j]);
                                ((GeneralIcon)SelectedIconArr[j]).ResetParent((GeneralIcon)SelectedIconArr[j]);
                                this.Controls.Remove(((GeneralIcon)SelectedIconArr[j]).IconPicBox);
                                this.Controls.Remove(((GeneralIcon)SelectedIconArr[j]).MoveToIconPicBox);
                                this.Controls.Remove(((GeneralIcon)SelectedIconArr[j]).InPic1);
                                this.Controls.Remove(((GeneralIcon)SelectedIconArr[j]).InPic2);
                                this.Controls.Remove(((GeneralIcon)SelectedIconArr[j]).OutPic1);
                                this.Controls.Remove(((GeneralIcon)SelectedIconArr[j]).OutPic2);
                                for (k = ((GeneralIcon)SelectedIconArr[j]).IconArrNum + 1; k < IconGeneralArr.Count; k++)
                                {
                                    ((GeneralIcon)IconGeneralArr[k]).IconArrNum--;
                                }
                                gpioEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                uartEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                UEcomEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                timeEventControl.Remove(IconGeneralArr[SelectedIconNum]);
                                IconGeneralArr.RemoveAt(((GeneralIcon)SelectedIconArr[j]).IconArrNum);
                            }
                            break;
                        default:
                            break;
                    }
                    for (k = 0; k < IconGeneralArr.Count; k++)
                    {
                        if (((GeneralIcon)(IconGeneralArr[k])).Parent == null)
                        {
                            ((GeneralIcon)(IconGeneralArr[k])).ResettingRelation((GeneralIcon)(IconGeneralArr[k]));
                        }
                    }
                }
                this.ReDraw();
                //[2021/4/28]加入音效播放
                sp.SoundLocation = Path.Combine(Globaldefine.exePath, "Config/delete.wav");
                sp.Play();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        /// <summary>复制图标 2015-5-16 【GZF】</summary>
        public void CopyIcon(ref LineLinkIconType Type, ref int Num, ref string Name, ref int PointX,
            ref int PointY, ref string[] Code, bool flag)
        {
            GeneralIcon tempGeneralIcon;
            try
            {
                if (this.SelectedIcon != null)
                {
                    //[2021/1/31]删除控件时control_Cnt对应控件减一,前提是控件数量大于0也就是有该控件
                    //[2021/3/22]
                    if (SelectedIcon.IconType == LinkIconType.GeneralIcon)
                        if (((GeneralIcon)SelectedIcon).GeneralIconType != GeneralIcon.TypeOfGeneralIcon.SensorIcon)
                        {
                        if (Globaldefine.loadConfig.control_Cnt.ContainsKey(this.SelectedIcon.ModuleName))
                            if (Globaldefine.loadConfig.control_Cnt[this.SelectedIcon.ModuleName] > 0)
                                Globaldefine.loadConfig.control_Cnt[this.SelectedIcon.ModuleName]++;
                            string moduleName = ((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName;
                            string iconName = moduleName;
                        bool isInner = !Globaldefine.loadConfig.control_Cnt.TryGetValue(moduleName, out int cnt);
                        if (!isInner)
                        {
                            if (cnt > 0)
                                iconName += cnt;
                            //只要添加一个控件 cnt就加一
                            Globaldefine.loadConfig.control_Cnt[moduleName]++;
                        }


                        if ((this.SelectedIconType != LineLinkIconType.NULL) && (this.SelectedIconNum != -1))
                        {
                            //判断复制的控件的类型
                            switch (this.SelectedIconType)
                            {
                                //通用控件
                                case LineLinkIconType.GeneralIcon:
                                    //开始控件不允许复制
                                    if (SelectedIconNum != 0)
                                    {
                                        Type = LineLinkIconType.GeneralIcon;
                                        Name = ((GeneralIcon)IconGeneralArr[SelectedIconNum]).ModuleName;
                                        //=========================20160426复制多个控件====================
                                        Globaldefine.CopyGeneralArr2.Clear();//20160607
                                                                             //禁止流程控件的配对节点单独复制
                                        if ((Name != "单分支End") && (Name != "双分支End1") && (Name != "双分支End2") && (Name != "计数循环End") &&
                                           (Name != "条件循环End"))
                                        {
                                            tempGeneralIcon = (GeneralIcon)IconGeneralArr[SelectedIconNum];
                                            //[2021/2/1] 这里的复制也要给控件改名
                                            //但是这里的改名有问题 牵扯到指针、引用 所以原来的名字也修改了
                                            tempGeneralIcon.IconName = iconName;
                                            //CopyGeneralArr.Add(tempGeneralIcon);
                                            Globaldefine.CopyGeneralArr2.Add(tempGeneralIcon);
                                            if ((Name == "单分支") || (Name == "计数循环") || (Name == "条件循环"))
                                            {
                                                while ((tempGeneralIcon.Child != null) && (tempGeneralIcon.IconArrNum != SelectedIconNum + 1))
                                                {
                                                    tempGeneralIcon = (GeneralIcon)tempGeneralIcon.Child;
                                                    //[2021/2/1] 这里的复制也要给控件改名
                                                    tempGeneralIcon.IconName = iconName;
                                                    // CopyGeneralArr.Add(tempGeneralIcon);
                                                    Globaldefine.CopyGeneralArr2.Add(tempGeneralIcon);
                                                }
                                            }
                                            if (Name == "双分支")//有两个结束节点"双分支End1"，"双分支End2"
                                            {
                                                while ((tempGeneralIcon.Child != null) && (tempGeneralIcon.IconArrNum != SelectedIconNum + 2))
                                                {
                                                    tempGeneralIcon = (GeneralIcon)tempGeneralIcon.Child;
                                                    //[2021/2/1] 这里的复制也要给控件改名
                                                    tempGeneralIcon.IconName = iconName;
                                                    // CopyGeneralArr.Add(tempGeneralIcon);
                                                    Globaldefine.CopyGeneralArr2.Add(tempGeneralIcon);
                                                }
                                            }
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        //flag==true,剪切操作,还需删除原先的控件
                        if (flag)
                        {
                            this.DeleteIcon();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        /// <summary>粘贴图标 2015-5-16 【GZF】</summary>
        public void PasteIcon(LineLinkIconType Type, int Num, string Name, int PointX,
           int PointY, string[] Code)
       
        {
            if (PastPointX != 0)//选定粘贴位置
            {
                PointX = PastPointX;
                PointY = PastPointY;
                PastPointX = PastPointY=0;//用后回0
            }
            GeneralIcon tempGeneralIcon;
            GeneralIcon tempGeneralIcon1=null;
            GeneralIcon tempGeneralIcon2;
            try
            {
               // if ((Type != LineLinkIconType.NULL)&&(CopyGeneralArr.Count>0))
                if ((Type != LineLinkIconType.NULL) && (Globaldefine.CopyGeneralArr2.Count > 0))
                {
                    switch (Type)
                    {
                        
                         case LineLinkIconType.GeneralIcon:
                           // for (int i = 0; i < CopyGeneralArr.Count; i++)//30160426修改粘贴流程体
                            for (int i = 0; i < Globaldefine.CopyGeneralArr2.Count; i++)//30160426修改粘贴流程体
                            {
                               // Name = ((GeneralIcon)CopyGeneralArr[i]).ModuleName;
                                Name = ((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).ModuleName;
                               // MessageBox.Show(i.ToString()+":"+ Name);
                                if ((Name != "单分支End") && (Name != "双分支End1") && (Name != "双分支End2") && (Name != "计数循环End") && (Name != "条件循环End"))
                                {
                                    tempGeneralIcon = new GeneralIcon();
                                    //if (((GeneralIcon)CopyGeneralArr[i]).IconFuncType == 1)//普通控件
                                    if (((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).IconFuncType == 1)//普通控件
                                       // ((GeneralIcon)tempGeneralIcon).CreateGeneralImage(((GeneralIcon)CopyGeneralArr[i]).GeneralIconType, ((GeneralIcon)CopyGeneralArr[i]).ModuleName, PointX + 6, PointY, this, false);
                                        ((GeneralIcon)tempGeneralIcon).CreateGeneralImage(((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).GeneralIconType, ((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).ModuleName, ((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).IconName, PointX + 6, PointY, this, false);
                                    else //子程序控件
                                        ((GeneralIcon)tempGeneralIcon).CreateGeneralImage(((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).GeneralIconType, ((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).ModuleName, ((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).IconName, PointX + 6, PointY, this, true);
                                   
                                    tempGeneralIcon.code.InsertCode = ((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).code.InsertCode;
                                    tempGeneralIcon.code.Comment = ((GeneralIcon)Globaldefine.CopyGeneralArr2[i]).code.Comment;
                                    if (Name == "计数循环")//对应循环体复制到其他子程序时，去除代码确保重建局部循环变量
                                    {
                                        tempGeneralIcon.code.InsertCode = "";
                                        tempGeneralIcon.code.Comment = "需重新设置循环次数！";
                                    }
                                    IconGeneralArr.Add(tempGeneralIcon);
                                    tempGeneralIcon.IconArrNum = IconGeneralArr.Count - 1;

                                    switch (Name)//对于以下控件名需配对形成它的结束节点
                                    {
                                        case "单分支":

                                            PointY += 5;
                                            GeneralIcon cndjudgeend = new GeneralIcon();
                                            cndjudgeend.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                                "单分支End", "单分支End",PointX + 6, PointY, this, false);
                                            cndjudgeend.code.InsertCode = "} //单分支结束";
                                            IconGeneralArr.Add(cndjudgeend);
                                            cndjudgeend.IconArrNum = IconGeneralArr.Count - 1;
                                            cndjudgeend.code.Comment = "单分支结束";  //20160324

                                            //20160125添加 关联END，建立父子关系
                                            ((GeneralIcon)tempGeneralIcon).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                                            ((GeneralIcon)tempGeneralIcon).Child = (GeneralIcon)cndjudgeend;
                                            ((GeneralIcon)tempGeneralIcon).ChildIconArrNum = cndjudgeend.IconArrNum; ;
                                            ((GeneralIcon)tempGeneralIcon).ChildDotX = ((GeneralIcon)tempGeneralIcon).IconLeftDotNum;
                                            ((GeneralIcon)tempGeneralIcon).ChildDotY = ((GeneralIcon)tempGeneralIcon).IconTopDotNum + 5;

                                            ((GeneralIcon)cndjudgeend).Parent = (GeneralIcon)tempGeneralIcon;//20160125添加 关联END
                                            ((GeneralIcon)cndjudgeend).ParentIconArrNum = tempGeneralIcon.IconArrNum;
                                            ((GeneralIcon)cndjudgeend).ParentType = GeneralIcon.LinkIconType.GeneralIcon;

                                            break;
                                        case "双分支":

                                            PointY += 5;
                                            GeneralIcon dcndjudgeend1 = new GeneralIcon();
                                            dcndjudgeend1.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                                    "双分支End1", "双分支End1", PointX + 6, PointY, this, false);
                                            dcndjudgeend1.code.InsertCode = "}\nelse\n{";
                                            IconGeneralArr.Add(dcndjudgeend1);
                                            dcndjudgeend1.IconArrNum = IconGeneralArr.Count - 1;
                                            dcndjudgeend1.code.Comment = "双分支条件真结束";  //20160324
                                            PointY += 5;
                                            GeneralIcon dcndjudgeend2 = new GeneralIcon();
                                            dcndjudgeend2.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                                "双分支End2", "双分支End2", PointX + 6, PointY, this, false);
                                            dcndjudgeend2.code.InsertCode = "} //双分支结束";
                                            IconGeneralArr.Add(dcndjudgeend2);
                                            dcndjudgeend2.IconArrNum = IconGeneralArr.Count - 1;
                                            dcndjudgeend2.code.Comment = "双分支结束";  //20160324
                                            //20160130添加 关联END，建立父子关系
                                            ((GeneralIcon)tempGeneralIcon).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                                            ((GeneralIcon)tempGeneralIcon).Child = (GeneralIcon)dcndjudgeend1;
                                            ((GeneralIcon)tempGeneralIcon).ChildIconArrNum = dcndjudgeend1.IconArrNum;
                                            ((GeneralIcon)tempGeneralIcon).ChildDotX = ((GeneralIcon)tempGeneralIcon).IconLeftDotNum;
                                            ((GeneralIcon)tempGeneralIcon).ChildDotY = ((GeneralIcon)tempGeneralIcon).IconTopDotNum + 5;

                                            ((GeneralIcon)dcndjudgeend1).Parent = (GeneralIcon)tempGeneralIcon;//20160130添加 关联END
                                            ((GeneralIcon)dcndjudgeend1).ParentIconArrNum = tempGeneralIcon.IconArrNum;
                                            ((GeneralIcon)dcndjudgeend1).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                                            ((GeneralIcon)dcndjudgeend1).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                                            ((GeneralIcon)dcndjudgeend1).Child = (GeneralIcon)dcndjudgeend2;
                                            ((GeneralIcon)dcndjudgeend1).ChildIconArrNum = dcndjudgeend2.IconArrNum;
                                            ((GeneralIcon)dcndjudgeend1).ChildDotX = ((GeneralIcon)dcndjudgeend1).IconLeftDotNum;
                                            ((GeneralIcon)dcndjudgeend1).ChildDotY = ((GeneralIcon)dcndjudgeend1).IconTopDotNum + 5;

                                            ((GeneralIcon)dcndjudgeend2).Parent = (GeneralIcon)dcndjudgeend1;//20160130添加 关联END
                                            ((GeneralIcon)dcndjudgeend2).ParentIconArrNum = dcndjudgeend1.IconArrNum;
                                            ((GeneralIcon)dcndjudgeend2).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                                            break;
                                        case "计数循环":

                                            PointY += 5;
                                            GeneralIcon countloopend = new GeneralIcon();
                                            countloopend.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                                "计数循环End", "计数循环End", PointX + 6, PointY, this, false);
                                            countloopend.code.InsertCode = "} //计数循环结束";
                                            IconGeneralArr.Add(countloopend);
                                            countloopend.IconArrNum = IconGeneralArr.Count - 1;
                                            countloopend.code.Comment = "计数循环结束";  //20160324
                                            //20160130添加 关联END，建立父子关系
                                            ((GeneralIcon)tempGeneralIcon).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                                            ((GeneralIcon)tempGeneralIcon).Child = (GeneralIcon)countloopend;
                                            ((GeneralIcon)tempGeneralIcon).ChildIconArrNum = countloopend.IconArrNum;
                                            ((GeneralIcon)tempGeneralIcon).ChildDotX = ((GeneralIcon)tempGeneralIcon).IconLeftDotNum;
                                            ((GeneralIcon)tempGeneralIcon).ChildDotY = ((GeneralIcon)tempGeneralIcon).IconTopDotNum + 5;

                                            ((GeneralIcon)countloopend).Parent = (GeneralIcon)tempGeneralIcon;//20160130添加 关联END
                                            ((GeneralIcon)countloopend).ParentIconArrNum = tempGeneralIcon.IconArrNum;
                                            ((GeneralIcon)countloopend).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                                            ((GeneralIcon)countloopend).Child = null;
                                            break;
                                        case "条件循环":

                                            PointY += 5;
                                            GeneralIcon cdnloopend = new GeneralIcon();
                                            cdnloopend.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                                "条件循环End", "条件循环End", PointX + 6, PointY, this, false);
                                            cdnloopend.code.InsertCode = "} //条件循环结束";
                                            IconGeneralArr.Add(cdnloopend);
                                            cdnloopend.IconArrNum = IconGeneralArr.Count - 1;
                                            cdnloopend.code.Comment = "条件循环结束";  //20160324
                                            //20160130添加 关联END，建立父子关系
                                            ((GeneralIcon)tempGeneralIcon).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                                            ((GeneralIcon)tempGeneralIcon).Child = (GeneralIcon)cdnloopend;
                                            ((GeneralIcon)tempGeneralIcon).ChildIconArrNum = cdnloopend.IconArrNum; ;
                                            ((GeneralIcon)tempGeneralIcon).ChildDotX = ((GeneralIcon)tempGeneralIcon).IconLeftDotNum;
                                            ((GeneralIcon)tempGeneralIcon).ChildDotY = ((GeneralIcon)tempGeneralIcon).IconTopDotNum + 5;

                                            ((GeneralIcon)cdnloopend).Parent = (GeneralIcon)tempGeneralIcon;//20160130添加 关联END
                                            ((GeneralIcon)cdnloopend).ParentIconArrNum = tempGeneralIcon.IconArrNum;
                                            ((GeneralIcon)cdnloopend).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                                            ((GeneralIcon)cdnloopend).Child = null;
                                            break;

                                        default:
                                           
                                            break;
                                    }
                                    //   建立与上一级的父子关系
                                    if (((GeneralIcon)tempGeneralIcon1) != null)//有前级父控件
                                    {
                                        // MessageBox.Show("tempGeneralIcon1 name:" + ((GeneralIcon)tempGeneralIcon1).ModuleName);
                                        if (((GeneralIcon)tempGeneralIcon1).Child != null)//前级有子控件
                                        {
                                            tempGeneralIcon2 = (GeneralIcon)tempGeneralIcon;
                                            while (((GeneralIcon)tempGeneralIcon2).Child != null)//要将前级子控件放在插入控件体后
                                            {
                                                tempGeneralIcon2 = (GeneralIcon)(((GeneralIcon)tempGeneralIcon2).Child);
                                            }
                                            ((GeneralIcon)tempGeneralIcon2).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                                            ((GeneralIcon)tempGeneralIcon2).Child = (GeneralIcon)(((GeneralIcon)tempGeneralIcon1).Child);
                                            ((GeneralIcon)tempGeneralIcon2).ChildIconArrNum = ((GeneralIcon)tempGeneralIcon1).ChildIconArrNum;
                                            ((GeneralIcon)tempGeneralIcon2).ChildDotX = ((GeneralIcon)tempGeneralIcon).IconLeftDotNum;
                                            ((GeneralIcon)tempGeneralIcon2).ChildDotY = ((GeneralIcon)tempGeneralIcon).IconTopDotNum + 5;

                                            ((GeneralIcon)((GeneralIcon)tempGeneralIcon1).Child).Parent = (GeneralIcon)tempGeneralIcon;// 
                                            ((GeneralIcon)((GeneralIcon)tempGeneralIcon1).Child).ParentIconArrNum = ((GeneralIcon)tempGeneralIcon).IconArrNum;
                                            ((GeneralIcon)((GeneralIcon)tempGeneralIcon1).Child).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                                        }
                                        ((GeneralIcon)tempGeneralIcon1).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                                        ((GeneralIcon)tempGeneralIcon1).Child = (GeneralIcon)tempGeneralIcon;
                                        ((GeneralIcon)tempGeneralIcon1).ChildIconArrNum = ((GeneralIcon)tempGeneralIcon).IconArrNum; ;
                                        ((GeneralIcon)tempGeneralIcon1).ChildDotX = ((GeneralIcon)tempGeneralIcon).IconLeftDotNum;
                                        ((GeneralIcon)tempGeneralIcon1).ChildDotY = ((GeneralIcon)tempGeneralIcon).IconTopDotNum + 5;

                                        ((GeneralIcon)tempGeneralIcon).Parent = (GeneralIcon)tempGeneralIcon1;// 
                                        ((GeneralIcon)tempGeneralIcon).ParentIconArrNum = ((GeneralIcon)tempGeneralIcon1).IconArrNum;
                                        ((GeneralIcon)tempGeneralIcon).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                                       
                                    }
                                    tempGeneralIcon1 = tempGeneralIcon;//保留当前的控件信息，以便与后级建立父子关系
                                }
                                else //为"单分支End"、 "双分支End1"、"双分支End2"、"计数循环End"、"条件循环End"情况
                                {
                                    if (((GeneralIcon)tempGeneralIcon1).Child != null)
                                        tempGeneralIcon1 = (GeneralIcon)(((GeneralIcon)tempGeneralIcon1).Child);//指向当前的Endx控件
                                }
                                
                                PointY += 5;
                       
                             }     
                             break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        ///==============================================================================
        #endregion

        #region frmGraphicProgrammer类的事件
        ///==============================================================================

        private void frmGraphicProgrammer_MouseUp(object sender, MouseEventArgs e)
        {
            //1.当前的操作是从树形控件视图中选择了控件图标要加载到设计面板中
            if (e.Button == MouseButtons.Left && Globaldefine.FrmParent.IconBoxOfForm.AlreadySelectIconFromTreeView)
            {
                int x = (int)(e.X / (Globaldefine.DotSize * 15)) -2;// 
                int y = (int)(e.Y / (Globaldefine.DotSize * 15)) - 2;
                // MessageBox.Show(x.ToString());
                //【2021/1/30 此处对控件进行重命名】
                //读取json中所有外设控件 初始化个数为0
                //[2021/3/22]

                SelectedIconFromTreeView selectedIconFromTreeView = Globaldefine.FrmParent.IconBoxOfForm.SelectedIconFromTreeViewInfo;
                string moduleName = selectedIconFromTreeView.selectedIconName;
                string iconName = moduleName;
                bool isInner = !Globaldefine.loadConfig.control_Cnt.TryGetValue(moduleName, out int cnt);
                //[2021/3/24]这些执行控件只要有一个即可
                if (moduleName == "小车" || moduleName == "彩灯" || moduleName == "数码管模块" || moduleName == "电机" || moduleName == "风扇模块"
                    || moduleName == "小灯" || moduleName == "内置三色灯" || moduleName == "蜂鸣器" || moduleName == "可调亮度小灯")
                    isInner = true;
                if (!isInner)
                {
                    if (cnt > 0)
                        iconName += cnt;
                    //只要添加一个控件 cnt就加一
                    Globaldefine.loadConfig.control_Cnt[moduleName]++;
                }

                switch (selectedIconFromTreeView.selectedIconType)
                {
                    case frmIconBox.selectedType.EventIcon:    //事件控件
                        GeneralIcon ex = new GeneralIcon();//GeneralIcon继承Icon的特性
                        ex.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.EventIcon,
                            selectedIconFromTreeView.selectedIconName, iconName, x, y, this, false);
                        IconGeneralArr.Add(ex);
                        //[2021/3/15]
                        if (ex.GeneralIconType == GeneralIcon.TypeOfGeneralIcon.EventIcon
                    && (ex.ModuleName == "红外循迹" || ex.ModuleName == "人体红外" ||
                    ex.ModuleName == "碰撞检测" || ex.ModuleName == "触发式开关"))
                        {
                            gpioEventControl.Add(ex);
                        }
                        if (ex.GeneralIconType == GeneralIcon.TypeOfGeneralIcon.EventIcon
                            && (ex.ModuleName == "接收到串口数据"))
                        {
                            uartEventControl.Add(ex);
                        }
                        if (ex.GeneralIconType == GeneralIcon.TypeOfGeneralIcon.EventIcon
                            && (ex.ModuleName == "接收到WIFI数据"))
                        {
                            UEcomEventControl.Add(ex);
                        }
                        if (ex.GeneralIconType == GeneralIcon.TypeOfGeneralIcon.EventIcon
                            && (ex.ModuleName == "定时器时间到"))
                        {
                            timeEventControl.Add(ex);
                        }
                        ex.IconArrNum = IconGeneralArr.Count - 1;
                        break;
                    case frmIconBox.selectedType.ExecuteIcon:    //执行控件
                        GeneralIcon zx = new GeneralIcon();//GeneralIcon继承Icon的特性
                        zx.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.ExecuteIcon,
                            selectedIconFromTreeView.selectedIconName, iconName, x, y, this, false);
                        IconGeneralArr.Add(zx);
                        zx.IconArrNum = IconGeneralArr.Count - 1;
                        break;
                    case frmIconBox.selectedType.SensorIcon:    //传感器控件
                        GeneralIcon sx = new GeneralIcon();
                        sx.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.SensorIcon,
                            selectedIconFromTreeView.selectedIconName, iconName, x, y, this, false);
                        IconGeneralArr.Add(sx);
                        sx.IconArrNum = IconGeneralArr.Count - 1;
                        sx.code.Comment = "未设置...";  //20160327
                        break;
                    //TODO 通信控件
                    case frmIconBox.selectedType.CommunicateIcon:   //通信控件
                        GeneralIcon tx = new GeneralIcon();
                        tx.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.CommunicateIcon,
                            selectedIconFromTreeView.selectedIconName, iconName, x, y, this, false);
                        IconGeneralArr.Add(tx);
                        tx.IconArrNum = IconGeneralArr.Count - 1;
                        tx.code.Comment = "未设置...";  //20160327
                        break;
                    case frmIconBox.selectedType.FlowControl://统一修改成GeneralIcon类型
                        if (selectedIconFromTreeView.selectedIconName == "单分支")
                        {
                            GeneralIcon cndjudge = new GeneralIcon();
                            cndjudge.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                selectedIconFromTreeView.selectedIconName, iconName, x, y, this, false);
                            IconGeneralArr.Add(cndjudge);
                            cndjudge.code.InsertCode = "if(1) \n{";
                            cndjudge.IconArrNum = IconGeneralArr.Count - 1;
                            cndjudge.code.Comment = "单分支条件：1";  //20160324

                            GeneralIcon cndjudgeend = new GeneralIcon();
                            cndjudgeend.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                "单分支End", "单分支End", x, y + 6, this, false);
                            cndjudgeend.code.InsertCode = "}  //单分支结束";
                            IconGeneralArr.Add(cndjudgeend);
                            cndjudgeend.IconArrNum = IconGeneralArr.Count - 1;
                            cndjudgeend.code.Comment = "单分支结束";  //20160324                                            

                            //20160125添加 关联END，建立父子关系
                            ((GeneralIcon)cndjudge).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                            ((GeneralIcon)cndjudge).Child = (GeneralIcon)cndjudgeend;
                            ((GeneralIcon)cndjudge).ChildIconArrNum = cndjudgeend.IconArrNum; ;
                            ((GeneralIcon)cndjudge).ChildDotX = ((GeneralIcon)cndjudge).IconLeftDotNum;
                            ((GeneralIcon)cndjudge).ChildDotY = ((GeneralIcon)cndjudge).IconTopDotNum + 8;

                            ((GeneralIcon)cndjudgeend).Parent = (GeneralIcon)cndjudge;//20160125添加 关联END
                            ((GeneralIcon)cndjudgeend).ParentIconArrNum = cndjudge.IconArrNum;
                            ((GeneralIcon)cndjudgeend).ParentType = GeneralIcon.LinkIconType.GeneralIcon;

                        }
                        else if (selectedIconFromTreeView.selectedIconName == "双分支")
                        {
                            GeneralIcon dcndjudge = new GeneralIcon();
                            dcndjudge.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                selectedIconFromTreeView.selectedIconName, iconName, x, y, this, false);
                            IconGeneralArr.Add(dcndjudge);
                            dcndjudge.code.InsertCode = "if(1) \n{";
                            dcndjudge.IconArrNum = IconGeneralArr.Count - 1;
                            dcndjudge.code.Comment = "双分支条件：1";  //20160324

                            GeneralIcon dcndjudgeend1 = new GeneralIcon();
                            dcndjudgeend1.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                "双分支End1", "双分支End1", x, y + 6, this, false);
                            dcndjudgeend1.code.InsertCode = "}\nelse\n{";
                            IconGeneralArr.Add(dcndjudgeend1);
                            dcndjudgeend1.IconArrNum = IconGeneralArr.Count - 1;
                            dcndjudgeend1.code.Comment = "双分支条件真结束";  //20160324

                            GeneralIcon dcndjudgeend2 = new GeneralIcon();
                            dcndjudgeend2.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                "双分支End2", "双分支End2", x, y + 12, this, false);
                            dcndjudgeend2.code.InsertCode = "} //双分支结束";
                            IconGeneralArr.Add(dcndjudgeend2);
                            dcndjudgeend2.IconArrNum = IconGeneralArr.Count - 1;
                            dcndjudgeend2.code.Comment = "双分支结束";  //20160324
                                                                    //20160130添加 关联END，建立父子关系
                            ((GeneralIcon)dcndjudge).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                            ((GeneralIcon)dcndjudge).Child = (GeneralIcon)dcndjudgeend1;
                            ((GeneralIcon)dcndjudge).ChildIconArrNum = dcndjudgeend1.IconArrNum;
                            ((GeneralIcon)dcndjudge).ChildDotX = ((GeneralIcon)dcndjudge).IconLeftDotNum;
                            ((GeneralIcon)dcndjudge).ChildDotY = ((GeneralIcon)dcndjudge).IconTopDotNum + 8;

                            ((GeneralIcon)dcndjudgeend1).Parent = (GeneralIcon)dcndjudge;//20160130添加 关联END
                            ((GeneralIcon)dcndjudgeend1).ParentIconArrNum = dcndjudge.IconArrNum;
                            ((GeneralIcon)dcndjudgeend1).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                            ((GeneralIcon)dcndjudgeend1).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                            ((GeneralIcon)dcndjudgeend1).Child = (GeneralIcon)dcndjudgeend2;
                            ((GeneralIcon)dcndjudgeend1).ChildIconArrNum = dcndjudgeend2.IconArrNum;
                            ((GeneralIcon)dcndjudgeend1).ChildDotX = ((GeneralIcon)dcndjudgeend1).IconLeftDotNum;
                            ((GeneralIcon)dcndjudgeend1).ChildDotY = ((GeneralIcon)dcndjudgeend1).IconTopDotNum + 8;

                            ((GeneralIcon)dcndjudgeend2).Parent = (GeneralIcon)dcndjudgeend1;//20160130添加 关联END
                            ((GeneralIcon)dcndjudgeend2).ParentIconArrNum = dcndjudgeend1.IconArrNum;
                            ((GeneralIcon)dcndjudgeend2).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                        }
                        else if (selectedIconFromTreeView.selectedIconName == "计数循环")
                        {
                            GeneralIcon countloop = new GeneralIcon();
                            countloop.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                selectedIconFromTreeView.selectedIconName, iconName, x, y, this, false);
                            IconGeneralArr.Add(countloop);
                            countloop.IconArrNum = IconGeneralArr.Count - 1;
                            countloop.code.Comment = "循环次数：未设定";  //20160324

                            GeneralIcon countloopend = new GeneralIcon();
                            countloopend.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                "计数循环End", "计数循环End", x, y + 6, this, false);
                            countloopend.code.InsertCode = "} //计数循环结束";
                            IconGeneralArr.Add(countloopend);
                            countloopend.IconArrNum = IconGeneralArr.Count - 1;
                            countloopend.code.Comment = "计数循环结束";  //20160324
                                                                    //20160130添加 关联END，建立父子关系
                            ((GeneralIcon)countloop).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                            ((GeneralIcon)countloop).Child = (GeneralIcon)countloopend;
                            ((GeneralIcon)countloop).ChildIconArrNum = countloopend.IconArrNum;
                            ((GeneralIcon)countloop).ChildDotX = ((GeneralIcon)countloop).IconLeftDotNum;
                            ((GeneralIcon)countloop).ChildDotY = ((GeneralIcon)countloop).IconTopDotNum + 8;

                            ((GeneralIcon)countloopend).Parent = (GeneralIcon)countloop;//20160130添加 关联END
                            ((GeneralIcon)countloopend).ParentIconArrNum = countloop.IconArrNum;
                            ((GeneralIcon)countloopend).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                            ((GeneralIcon)countloopend).Child = null;

                        }
                        else if (selectedIconFromTreeView.selectedIconName == "条件循环")
                        {
                            GeneralIcon cdnloop = new GeneralIcon();
                            cdnloop.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                selectedIconFromTreeView.selectedIconName, iconName, x, y, this, false);
                            IconGeneralArr.Add(cdnloop);
                            cdnloop.code.InsertCode = "while(1) \n{";
                            cdnloop.IconArrNum = IconGeneralArr.Count - 1;
                            cdnloop.code.Comment = "循环条件：1";  //20160324

                            GeneralIcon cdnloopend = new GeneralIcon();
                            cdnloopend.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.FlowControl,
                                "条件循环End", "条件循环End", x, y + 6, this, false);
                            cdnloopend.code.InsertCode = "} //条件循环结束";
                            IconGeneralArr.Add(cdnloopend);
                            cdnloopend.IconArrNum = IconGeneralArr.Count - 1;
                            cdnloopend.code.Comment = "条件循环结束";  //20160324
                                                                    //20160130添加 关联END，建立父子关系
                            ((GeneralIcon)cdnloop).ChildType = GeneralIcon.LinkIconType.GeneralIcon;
                            ((GeneralIcon)cdnloop).Child = (GeneralIcon)cdnloopend;
                            ((GeneralIcon)cdnloop).ChildIconArrNum = cdnloopend.IconArrNum; ;
                            ((GeneralIcon)cdnloop).ChildDotX = ((GeneralIcon)cdnloop).IconLeftDotNum;
                            ((GeneralIcon)cdnloop).ChildDotY = ((GeneralIcon)cdnloop).IconTopDotNum + 8;

                            ((GeneralIcon)cdnloopend).Parent = (GeneralIcon)cdnloop;//20160130添加 关联END
                            ((GeneralIcon)cdnloopend).ParentIconArrNum = cdnloop.IconArrNum;
                            ((GeneralIcon)cdnloopend).ParentType = GeneralIcon.LinkIconType.GeneralIcon;
                            ((GeneralIcon)cdnloopend).Child = null;
                        }
                        break;
                    case frmIconBox.selectedType.SubFunIcon:
                        GeneralIcon sub = new GeneralIcon();
                        sub.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.ExecuteIcon,
                            selectedIconFromTreeView.selectedIconName, iconName, x, y, this, true);
                        IconGeneralArr.Add(sub);
                        sub.IconArrNum = IconGeneralArr.Count - 1;
                        sub.code.InsertCode = selectedIconFromTreeView.selectedIconName + "();";
                        //sub.code.Comment="功能子程序";  //20160324
                        sub.code.Comment = "功能子程序" + selectedIconFromTreeView.selectedIconName;
                        break;
                    //【20210513】根据树节点类型生成控件
                    case frmIconBox.selectedType.VarIcon:
                        GeneralIcon var = new GeneralIcon();
                        var.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.ExecuteIcon,
                            selectedIconFromTreeView.selectedIconName, iconName, x, y, this, true);
                        IconGeneralArr.Add(var);
                        var.IconArrNum = IconGeneralArr.Count - 1;
                        //var.code.InsertCode = selectedIconFromTreeView.selectedIconName + "();";
                        //sub.code.Comment="功能子程序";  //20160324
                        //sub.code.Comment = "功能子程序" + selectedIconFromTreeView.selectedIconName;
                        break;
                    
                    default:
                        return;
                }
                Globaldefine.FrmParent.IconBoxOfForm.AlreadySelectIconFromTreeView = false;
                this.Cursor = System.Windows.Forms.Cursors.Default;
                Globaldefine.FrmParent.IconBoxOfForm.Cursor = System.Windows.Forms.Cursors.Default;
            }
            //2.取消从树形控件视图中选择了控件图标要加载到设计面板中的操作
            else if (e.Button == MouseButtons.Right && Globaldefine.FrmParent.IconBoxOfForm.AlreadySelectIconFromTreeView)
            {

                Globaldefine.FrmParent.IconBoxOfForm.AlreadySelectIconFromTreeView = false;
                this.Cursor = System.Windows.Forms.Cursors.Default;
                Globaldefine.FrmParent.IconBoxOfForm.Cursor = System.Windows.Forms.Cursors.Default;
            }
            //3.取消画了一半的连接线
            else if ((e.Button == MouseButtons.Right) && (this.BFirstClickOutDot == true))
            {
                this.BFirstClickOutDot = false;
                this.m_OutIcon = null;
                this.m_OutIconModule = LineLinkIconType.NULL;
                this.ReDraw();
                PointStartSelect = false;
            }
            else if (PointStartSelect && !Globaldefine.FrmParent.MoveOrComCursor)//画范围框起点已选择，鼠标正常操作
            {   //4.画范围框的起点      // true:拖动工作区操作,false:正常操作
                int i;
            
                for (i = 0; i < SelectedIconArr.Count; i++)
                {
                    ((Icon)SelectedIconArr[i]).IconPicBox.BackColor = Color.Transparent;
                }
                SelectedIconArr.Clear();
                if (PointSelectX != e.X && PointSelectY != e.Y)
                {
                    int lX = -1;
                    int lY = -1;
                    int RX = -1;
                    int RY = -1;
                    if (PointSelectX < e.X && PointSelectY < e.Y)
                    {
                        lX = PointSelectX / (int)(Globaldefine.DotSize * 15);
                        lY = PointSelectY / (int)(Globaldefine.DotSize * 15);
                        RX = e.X / (int)(Globaldefine.DotSize * 15);
                        RY = e.Y / (int)(Globaldefine.DotSize * 15);
                    }
                    else if (PointSelectX < e.X && PointSelectY > e.Y)
                    {
                        lX = PointSelectX / (int)(Globaldefine.DotSize * 15);
                        lY = e.Y / (int)(Globaldefine.DotSize * 15);
                        RX = e.X / (int)(Globaldefine.DotSize * 15);
                        RY = PointSelectY / (int)(Globaldefine.DotSize * 15);
                    }
                    else if (PointSelectX > e.X && PointSelectY > e.Y)
                    {
                        lX = e.X / (int)(Globaldefine.DotSize * 15);
                        lY = e.Y / (int)(Globaldefine.DotSize * 15);
                        RX = PointSelectX / (int)(Globaldefine.DotSize * 15);
                        RY = PointSelectY / (int)(Globaldefine.DotSize * 15);
                    }
                    else if (PointSelectX > e.X && PointSelectY < e.Y)
                    {
                        lX = e.X / (int)(Globaldefine.DotSize * 15);
                        lY = PointSelectY / (int)(Globaldefine.DotSize * 15);
                        RX = PointSelectX / (int)(Globaldefine.DotSize * 15);
                        RY = e.Y / (int)(Globaldefine.DotSize * 15);
                    }
                    foreach (GeneralIcon g in IconGeneralArr)
                    {
                        if (g.IconLeftDotNum >= lX && g.IconLeftDotNum + 4 <= RX
                            && g.IconTopDotNum >= lY && g.IconTopDotNum + 4 <= RY)
                        {
                            SelectedIconArr.Add(g);
                        }
                    }
                }
                this.ReDraw();

            }
            else if (Globaldefine.FrmParent.MoveOrComCursor && PointStartSelect)
            {     //5.画范围框起点已选择，鼠标拖动操作
                try
                {
                    int i;
                    int dotchangeX = 0;
                    int dotchangeY = 0;

                    dotchangeX = (e.X - PointSelectX) / (int)(Globaldefine.DotSize * 15);
                    dotchangeY = (e.Y - PointSelectY) / (int)(Globaldefine.DotSize * 15);

                    //通用控件
                    for (i = 0; i < IconGeneralArr.Count; i++)
                    {
                        ((GeneralIcon)IconGeneralArr[i]).IconLeftDotNum += dotchangeX;
                        ((GeneralIcon)IconGeneralArr[i]).IconTopDotNum += dotchangeY;
                        ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Left = (int)(((GeneralIcon)IconGeneralArr[i]).IconLeftDotNum * Globaldefine.DotSize * 15);
                        ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Top = (int)(((GeneralIcon)IconGeneralArr[i]).IconTopDotNum * Globaldefine.DotSize * 15);
                        ((GeneralIcon)IconGeneralArr[i]).MoveToIconPicBox.Left = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Left;
                        ((GeneralIcon)IconGeneralArr[i]).MoveToIconPicBox.Top = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Top;
                        ((GeneralIcon)IconGeneralArr[i]).InPic1.Left = 0;
                        ((GeneralIcon)IconGeneralArr[i]).InPic1.Top = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.ClientSize.Height / 2 - ((GeneralIcon)IconGeneralArr[i]).InPic1.Height / 2;
                        ((GeneralIcon)IconGeneralArr[i]).InPic2.Left = 0;
                        ((GeneralIcon)IconGeneralArr[i]).InPic2.Top = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.ClientSize.Height / 2 - ((GeneralIcon)IconGeneralArr[i]).InPic2.Height / 2;
                        ((GeneralIcon)IconGeneralArr[i]).OutPic1.Left = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.ClientSize.Width - ((GeneralIcon)IconGeneralArr[i]).OutPic1.Width;
                        ((GeneralIcon)IconGeneralArr[i]).OutPic1.Top = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.ClientSize.Height / 2 - ((GeneralIcon)IconGeneralArr[i]).OutPic1.Height / 2;
                        ((GeneralIcon)IconGeneralArr[i]).OutPic2.Left = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.ClientSize.Width - ((GeneralIcon)IconGeneralArr[i]).OutPic2.Width;
                        ((GeneralIcon)IconGeneralArr[i]).OutPic2.Top = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.ClientSize.Height / 2 - ((GeneralIcon)IconGeneralArr[i]).OutPic2.Height / 2;
                        if (((GeneralIcon)IconGeneralArr[i]).notePic.Visible)
                        {
                            ((GeneralIcon)IconGeneralArr[i]).notePic.Left = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Left + ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Width / 2 - ((GeneralIcon)IconGeneralArr[i]).notePic.Width / 2;
                            ((GeneralIcon)IconGeneralArr[i]).notePic.Top = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Top - ((GeneralIcon)IconGeneralArr[i]).notePic.Height * 3 / 5;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else if (e.Button == MouseButtons.Right)
            { //6.只是点击右键，显示快捷菜单，粘贴
                FlowContextMenuStrip.Show(this,e.X, e.Y);
                PastPointX = (int)(e.X / (Globaldefine.DotSize * 15)) - 6;
                PastPointY = (int)(e.Y / (Globaldefine.DotSize * 15))-1; 
            }
            if (e.Button == MouseButtons.Left)
            {//7.只是点击左键，取消一些获得的操作等
                if (this.SelectedIcon != null)
                {
                    this.SelectedIcon.IconPicBox.BackColor = Color.Transparent;
                    this.SelectedIcon.MoveToIconPicBox.BackColor = Color.Transparent;
                    this.SelectedIcon = null;
                }
                if (PointStartSelect == false)
                {
                    int i;
                    for (i = 0; i < SelectedIconArr.Count; i++)
                    {
                        ((Icon)SelectedIconArr[i]).IconPicBox.BackColor = Color.Transparent;
                    }
                    SelectedIconArr.Clear();
                }
                PointStartSelect = false;
            }
        }
        //===========================================================================
        private void frmGraphicProgrammer_MouseMove(object sender, MouseEventArgs e)
        {
            if (Globaldefine.FrmParent.IconBoxOfForm.AlreadySelectIconFromTreeView)
            {
                this.Cursor = System.Windows.Forms.Cursors.Hand;
            }
            else if (this.BFirstClickOutDot)
            {
                this.lineEndX = e.X;
                this.lineEndY = e.Y;
                this.ReDraw();
                PointStartSelect = false;
            }                                            //正常操作false还是拖动工作区操作true
            else if (e.Button == MouseButtons.Left && !Globaldefine.FrmParent.MoveOrComCursor)//这里为正常操作
            {
                if (PointStartSelect)
                {
                    Graphics g = this.CreateGraphics();
                    BufferedGraphicsContext context = BufferedGraphicsManager.Current;
                    BufferedGraphics bg = context.Allocate(g, this.ClientRectangle);

                    this.ReDraw(bg);
                    Pen p = new Pen(Brushes.Blue, Globaldefine.DotSize * 3)
                    {
                        DashStyle = DashStyle.Dot
                    };
                    bg.Graphics.DrawPolygon(p,
                        new Point[] {new Point(PointSelectX, PointSelectY), 
                                 new Point(PointSelectX, e.Y),
                                 new Point(e.X, e.Y),
                                 new Point(e.X, PointSelectY)});


                    bg.Render();
                    bg.Dispose();
                    //bg = null;

                    PointStartSelect = true;
                }
            }
        }
        //===========================================================================
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);  
            this.ReDraw();
        }
        //===========================================================================
        private void frmGraphicProgrammer_Load(object sender, EventArgs e)
        {
            //添加"开始"控件
            GeneralIcon main = new GeneralIcon();
            main.CreateGeneralImage(GeneralIcon.TypeOfGeneralIcon.ExecuteIcon,
                "开始", "开始", 2, 2, this, false);
            IconGeneralArr.Add(main);
            main.IconArrNum = IconGeneralArr.Count - 1;
            main.code.Comment = "程序开始";
            if (this.SelectedIcon != null)
            {
                this.SelectedIcon.IconPicBox.BackColor = Color.Transparent;
                this.SelectedIcon.MoveToIconPicBox.BackColor = Color.Transparent;
            }
            this.SelectedIcon = main;
            // [2021/3/11]加载好图形化编程面板之后 就可以通知配置终端进行初始化

        }
        //===========================================================================
        //重写函数，虽未被工程引用，但实际会调用到，不可删除
        protected override void OnKeyUp(KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                //删除所选控件图标
                case Keys.Delete:
                    this.DeleteIcon();
                    this.CreateCode();
                    break;
                default:
                    break;
            }
            base.OnKeyDown(e);
        }
        //===========================================================================
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            if ((GetKeyState((int)(Keys.LShiftKey)) & 0x8000) != 0)
            {
                if (e.Delta * SystemInformation.MouseWheelScrollLines / 120 > 0)
                {
                    UpOrDownIcon(1, true);
                }
                else if (e.Delta * SystemInformation.MouseWheelScrollLines / 120 < 0)
                {
                    UpOrDownIcon(1, false);
                }
            }
            else
            {
                if (e.Delta * SystemInformation.MouseWheelScrollLines / 120 > 0)
                {
                    UpOrDownIcon(2, true);
                }
                else if (e.Delta * SystemInformation.MouseWheelScrollLines / 120 < 0)
                {
                    UpOrDownIcon(2, false);
                }
            }
            base.OnMouseWheel(e);
        }
        //===========================================================================
        private void UpOrDownIcon(int direction, bool flag)
        {
            int dotchangeX = 0;
            int dotchangeY = 0;

            Globaldefine.FrmParent.ModifyProgrammer = true;
            if (direction == 1)//左右滚动
            {
                if (flag == true)
                {
                    dotchangeX = 2;//右移动
                }
                else if (flag == false)
                {
                    dotchangeX = -2;//左移动
                }
                dotchangeY = 0;
            }
            else if (direction == 2)//上下滚动
            {
                if (flag == true)
                {
                    dotchangeY = 2;//下滚动
                }
                else if (flag == false)
                {
                    dotchangeY = -2;//上滚动
                }
                dotchangeX = 0;
            }
            try
            {
                int i;
                //通用控件
                for (i = 0; i < IconGeneralArr.Count; i++)
                {
                    ((GeneralIcon)IconGeneralArr[i]).IconLeftDotNum += dotchangeX;
                    ((GeneralIcon)IconGeneralArr[i]).IconTopDotNum += dotchangeY;
                    ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Left = (int)(((GeneralIcon)IconGeneralArr[i]).IconLeftDotNum * Globaldefine.DotSize * 15);
                    ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Top = (int)(((GeneralIcon)IconGeneralArr[i]).IconTopDotNum * Globaldefine.DotSize * 15);
                    ((GeneralIcon)IconGeneralArr[i]).MoveToIconPicBox.Left = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Left;
                    ((GeneralIcon)IconGeneralArr[i]).MoveToIconPicBox.Top = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.Top;
                    ((GeneralIcon)IconGeneralArr[i]).InPic1.Left =((GeneralIcon)IconGeneralArr[i]).IconPicBox.ClientSize.Width/ 2 - ((GeneralIcon)IconGeneralArr[i]).InPic1.Width/ 2;
                    ((GeneralIcon)IconGeneralArr[i]).InPic1.Top =0;       //20151206修改接点图标的位置，输入在上方，输出在下方。
                    ((GeneralIcon)IconGeneralArr[i]).InPic2.Left = ((GeneralIcon)IconGeneralArr[i]).InPic1.Left;
                    ((GeneralIcon)IconGeneralArr[i]).InPic2.Top = 0;     //ClientSize代表在缓冲区的大小，这里不能直接IconPicBox.Width，否则出现无法加载连线小图标
                    ((GeneralIcon)IconGeneralArr[i]).OutPic1.Left = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.ClientSize.Width/2 - ((GeneralIcon)IconGeneralArr[i]).OutPic1.Width/2;
                    ((GeneralIcon)IconGeneralArr[i]).OutPic1.Top = ((GeneralIcon)IconGeneralArr[i]).IconPicBox.ClientSize.Height - ((GeneralIcon)IconGeneralArr[i]).OutPic1.Height;
                    ((GeneralIcon)IconGeneralArr[i]).OutPic2.Left =((GeneralIcon)IconGeneralArr[i]).OutPic1.Left -2 ;
                    ((GeneralIcon)IconGeneralArr[i]).OutPic2.Top = ((GeneralIcon)IconGeneralArr[i]).OutPic1.Top -4 ;
                }
              for (i = 0; i < IconGeneralArr.Count; i++)
               {
                   SetRelation((GeneralIcon)IconGeneralArr[i]);//20151207调整连接控件，使其排成一列。
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
     //  20160317
        public void FlowContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
           
            switch (e.ClickedItem.ToString())
            {
                case "粘贴":
                    Globaldefine.FrmParent.ContextString = "粘贴";
                    break;
                default:
                    break;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Globaldefine.labelvisible)
            {
               
                this.textBoxIconNote.Visible = true;
               // this.textBoxIconNote.Enabled = true;
                this.textBoxIconNote.Location = new System.Drawing.Point(Globaldefine.label_X, Globaldefine.label_Y);
                this.textBoxIconNote.Text = Globaldefine.labelstring;
            }
            else
            {
                this.textBoxIconNote.Visible = false;
                this.textBoxIconNote.Enabled = false;
            }
        }
        ///==============================================================================
        #endregion
    }
}